【发布时间】:2022-01-02 02:53:27
【问题描述】:
Scanner input = new Scanner(System.in);
String sentence , invertedsentence = "";
int total , x;
System.out.print("Enter your sentence:");
sentence = input.nextLine();
total = sentence.length();
我正在尝试反转输入中的字符
for ( x = total-1 ; x < 1 ; x--){
invertedsentence = invertedsentence + sentence.charAt(x);
}
输出显示空白
System.out.println(invertedsentence);
【问题讨论】:
-
为什么?既然我需要反转字符串,那么它应该是从最后一个位置访问到第一个位置,不是吗?
-
for中间的条件是while条件,而不是until条件。所以Janez Kuhar 是对的 -
哦,我明白了。谢谢!
-
@CopperCleric 作为旁注,习惯于在不再需要资源时关闭它们。您的扫描仪对象应该关闭。这适用于所有 I/O 资源。这是您在开始为实际应用程序编码之前应该学习的重要一课。