简体   繁体   中英

Using loops to reverse a string

I am having trouble doing a task whereby someone enters a multiple line string, and I read the string and output each word in reverse in the exact same spot (whitespace and line breaks the same). After inputting how many words the user wants to reverse they type "done" to basically stop the loop.

Eg. input:

hey hello
world
done

output:

yeh olleh
dlrow

heres my code in which the loop never stops and does not scan the second line.

import java.util.Scanner;

public class LabProgram {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        String input = scnr.next();
        String reverse = "";

        while (!input.equals("done")) {
            for (int i = input.length() - 1; i >= 0; i--) {
                reverse = reverse + input.charAt(i);
            }
            System.out.println(reverse);
        }
    }
}

The loop you want to print the input word reversed is this:

Scanner scnr = new Scanner(System.in);
String input = scnr.next();

for (int i=input.length()-1; i >= 0; --i) {
    System.out.print(input.charAt(i));
}

Note that I use print() rather than println() , as you want to view the reversed input on the same line.

As for accepting user inputs while the loop is running, if you want that, you should break to stop printing based on some user input.

You were close. I simply changed your outer while loop slightly to both take in the input and check for the termination string. It will now reverse what ever you type in but will stop if you type in done .

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String input;
    while (!(input = scnr.nextLine()).equalsIgnoreCase("Done")) {
    
    String reverse = "";
    
        for (int i = input.length() - 1; i >= 0; i--) {
            reverse = reverse + input.charAt(i);
        }
        System.out.println(reverse);
    }
}

To simplify the code, you can use an enhanced for loop instead of reversed for loop and swap the summands inside:

String str = "hello world", reverse = "";

for (char ch : str.toCharArray())
    reverse = ch + reverse;

System.out.println(reverse); // dlrow olleh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM