嗨,我正在完成一项任务,但是我得到了错误的输出。
该项目的目标是反转字符串。
所以它应该接受一行文本作为输入,然后反向输出这行文本。程序重复执行,当用户为文本行输入"Done“、"done”或"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找不到我做错了什么。
发布于 2021-11-16 04:19:11
/*
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发布于 2021-11-16 06:30:12
您正在使用.equals()检查该行是否等于您的某个分隔词,但是您为它提供了输入Hello there Hey done,因此它不会检测分隔词(忽略您给了它完成,而不是退出的事实,我假设这是一个拼写错误),因此,要检测它,您必须检查该行是否包含该单词,如果包含,则切换一个布尔值,并从该行中删除该单词及其后面的任何文本,例如:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
boolean end = false;
while (!end) {
str = scnr.nextLine();
if (str.contains("quit") || str.contains("Quit") || str.contains("q")) { // checks if str contains the word, so if you write "hello quit" it will still detect it.
str = str.substring(0,str.toLowerCase().indexOf("q")); // cuts off the string from the q.
end = true;
}
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}否则,您只需要将quit添加到后面的行中,然后它就可以工作了,所以您可以输入Hello there Hey,然后按enter键,然后输入quit,这样就可以了。
https://stackoverflow.com/questions/69983468
复制相似问题