Home > other >  Reversing strings in Java (loops) until "done"
Reversing strings in Java (loops) until "done"

Time:05-04

this is a lab for class I'm trying to do. Here's the instructions: Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.

Ex: If the input is:

"Hello there

Hey

done"

the output is:

"ereht olleH

yeH"

And here's what I have right now:


public class LabProgram {
   public static void main(String[] args) {
      /* Type your code here. */
      Scanner scnr = new Scanner(System.in);
      String[] inputs = new String[100];
      String input;
      int i = 0;
      while (true) {
         input = scnr.nextLine();
         if(input.equals("Done") || input.equals("done") || input.equals("d"))
            break;
      inputs[i] = input;
      i  ;
         }
      for (int j = 0; j < i; j  ) {
         int length = inputs[j].length();
         String reverse = "";
         for (int k = length - i; k >= 0; k--) {
            reverse = reverse   inputs[j].charAt(k);
         }
         System.out.print("\n"   reverse);
      }
   }
}

Current output

What am I doing wrong??

CodePudding user response:

Iterate through the array, and reverse elements at every index. This solution is time consuming but does your job

 for (int j = 0; j < inputs.lenght; j  ) {
     int length = inputs[j].length();
    char a;
    String rev = "";
    for(int i =0; i< length; i  ){
        a = inputs[j].charAt(i);
        rev = a   rev;   
    }
     System.out.println(rev);
  }
    

CodePudding user response:

*Try to use StringBuilder And use method reverse -- @Artur Todeschini

To add to what Artur said, an ArrayList of StringBuilders could do the trick quite well:

for(StringBuilder nextEntry: stringBuilderList)
{
    nextEntry.reverse();
}

The enhanced for-loop will go through each entry in the ArrayList, and the StringBuilder's reverse will change the order of the letters.

EDIT TO SHOW FORMATTING

ArrayList<StringBuilder> stringBuilderList= new ArrayList<>();

*"note. given that this is for a lab, its probably for learning purposes and using built-in classes that does all the work for you are usually not the intended solution." -- @experiment unit 1998X

CodePudding user response:

Try to use StringBuilder And use method reverse

CodePudding user response:

This is another "ArrayList and StringBuilder-less" version.

String nextString = stringArray[i];
int length = nextString.length() - 1;
for(int j = 0; j < (length / 2); j  )
{
    char temp = nextString.charAt(j);
    nextString.setCharAt[j] = nextString.setCharAt[length - j];
    nextString.setCharAt[length - j] = temp;
}

NOTE

This is an inner loop for a String array and is NOT complete code

  •  Tags:  
  • java
  • Related