我在将所有行输入变为标准输入并将它们以相反顺序写入标准输出时遇到问题。即,以与输入相反的顺序输出每一行。下面是我的编码:
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by
\"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
append += input + " ";
}
sc.close();
System.out.println("The current append: " + append);
String stringArray[] = append.split(" strings" + "");
System.out.println("\n\nThe reverse order is:\n");
for (int i = 0; i < stringArray.length; i++) {
System.out.println(stringArray[i]);
}
}
}
下面是我的错误输出:
run:
Type some text with line breaks, end by "-1":
My name is John.
David is my best friend.
James also is my best friend.
-1
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
My name is John. David is my best friend. James also is my best friend.
BUILD SUCCESSFUL (total time: 16 seconds)
我想要如下所示的成功输出:
run:
Type some text with line breaks, end by "-1":
My name is John.
David is my best friend.
James also is my best friend.
-1
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
James also is my best friend.
David is my best friend.
My name is John.
BUILD SUCCESSFUL (total time: 16 seconds)
任何人都可以帮助我检查编码错误,并希望可以解决输出逆序问题并逐行处理吗?谢谢。
而不是将input附加到append字符串,您应该将输入字符串添加到List,然后从底部开始打印,或者使用Collections.reverse()] >方法,然后直接打印