我正在尝试反向打印字符串。即
hello world
应该显示为:
dlrow olleh
但结果只显示第一个单词的相反。即
olleh
有什么想法吗?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Input a string:");
String s;
s = input.next();
String original, reverse = "";
original = s;
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
input.close();
}
}
最佳答案
使用input.next()
仅存储变量中的下一个单词(仅“hello”)。试试这个:
System.out.println("Input a string:");
String s;
s = input.nextLine();
System.out.println("entered: " + s);
关于java - 向后打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22430801/