232k views
0 votes
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 "Quit", "quit", or "q" for the line of text. in java.

User AB Vyas
by
7.3k points

1 Answer

1 vote

Answer:

The solution code is as below:

  1. Scanner input = new Scanner(System.in);
  2. System.out.print("Input a string: ");
  3. String inStr = input.nextLine();
  4. int strLen = inStr.length();
  5. while(inStr.equals("Quit") != true && inStr.equals("quit") !=true && inStr.equals("q") != true){
  6. for(int i= 0; i < strLen; i++){
  7. System.out.print(inStr.charAt(strLen - 1 - i));
  8. }
  9. System.out.println();
  10. System.out.print("Input a string: ");
  11. inStr = input.nextLine();
  12. strLen = inStr.length();

Step-by-step explanation:

Firstly, we create a Scanner object, input (Line 1).

Next, we use the Scanner object nextLine() method to get a text input from user (Line 3).

We create a while loop and set the condition so long as the input text is not equal to "Quit", "quit" or "q" (Line 6), the program should proceed to print the input text in reverse (Line 8-10). To print the text in reverse, we can apply the expression length of string - 1 - current index. This will ensure the individual letter is read from the last and print the text in reverse.

Next, prompt the user to input a new text (Line 13-14) and repeat the same process of printing text in reverse so long as the current input text is not "Quit", "quit" or "q".

User Antiez
by
6.6k points