java - Java 项目输出
问题描述
嗨,我正在完成一项作业,但是我得到了错误的输出。
该项目的目标是反转字符串。
所以它应该将一行文本作为输入,并反向输出该行文本。程序重复,当用户输入“完成”、“完成”或“d”作为文本行时结束。
例如:如果输入是:
Hello there
Hey
done
输出是:
ereht olleH
yeH
我的代码:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
while (true) {
str = scnr.nextLine();
if (str.equals("quit") || str.equals("Quit") || str.equals("q")) break;
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
}
我当前的代码是,但是输出返回为:
输入
Hello there
Hey
done
输出
ereht olleH
yeH
enod
预期产出
ereht olleH
无法弄清楚我做错了什么。
解决方案
/*
I don't know what you know, so I am not sure how your professor
wants you to complete this, but I will do what comes to mind for myself.
*/
//Instead of while(true) I like to use do while, which runs once automatically, and continues running until a condition is met
do {
str = scnr.nextLine();
int i = 0;
//This isn't the cleanest way to solve this, especially because it doesn't remove the space before done.
//You could add more if statements for that, but the cleanest way would be to split the words into a String array
// and check if any of the values of the array equal done, and remove it before flipping it around
if(str.toLowerCase().contains("done"))
i = 4;
else if(str.toLowerCase().contains("d"))
i = 1;
while (i < str.length()) {
System.out.print(str.charAt(str.length() - i - 1));
i++;
}
System.out.println();
}
while (!str.toLowerCase().contains("done") || !str.toLowerCase().contains("d")); //This replaces that if statement from before
推荐阅读
- r - 如何让 R 为日期创建一列?
- python - 泡菜字符串与泡菜数字,硬盘上不同的泡菜文件大小
- httpclient - 是什么让 HttpSession 具有独特的 HTTP 客户端?
- pandas-groupby - 如何在熊猫中分组并制表值频率
- json - 勘误表 jmeter 提取器上 JMESpath 的不同行为
- laravel - 我在 laravel 中遇到不支持的邮件传输 [sendgrid] 错误
- python - 无法在 Azure 上安装 psycopg2
- json - 如何读取和打印 JSON 数组元素
- css - 背景图像:线性渐变在 Safari 中不起作用
- javascript - JavaScript forEach:如何计算 forEach 函数写入的行数?