Java 将程序循环回起始点(在它之后';完成了
所以我创建了这个程序,通过将第一个字符移动到单词的末尾,将单词的其余部分向后拼写,然后检查原始单词和新词是否相同,来操作用户输入的单词。它被设计为运行,直到用户输入单词“退出”作为所选单词。我已经设法让大部分代码正常工作,除了在检查了上一个单词后,它不再循环返回请求用户输入一个新单词,而是永远继续运行。我目前得到的代码如下:Java 将程序循环回起始点(在它之后';完成了,java,loops,if-statement,Java,Loops,If Statement,所以我创建了这个程序,通过将第一个字符移动到单词的末尾,将单词的其余部分向后拼写,然后检查原始单词和新词是否相同,来操作用户输入的单词。它被设计为运行,直到用户输入单词“退出”作为所选单词。我已经设法让大部分代码正常工作,除了在检查了上一个单词后,它不再循环返回请求用户输入一个新单词,而是永远继续运行。我目前得到的代码如下: package uploadTask9_wordPlay; import java.util.Scanner; public class wordPlay {
package uploadTask9_wordPlay;
import java.util.Scanner;
public class wordPlay {
public static void main(String[] args) {
// creates scanner object to get a name from the user input
Scanner userInput = new Scanner(System.in);
System.out.println("Enter a name to be tested, or 'quit' to exit
program: ");
// stores the user input into string testedName
String testedName = userInput.nextLine();
// if the user input is "quit", program exits
if (testedName.equals("quit")) {
System.out.println("Thanks for using the program");
System.exit(0);
}
// else, do the rest of the code with the given word
else {
while (testedName != "quit") {
// takes first character from userInput
char firstLetter = testedName.charAt(0);
// removes first character from testedName
StringBuilder removeChar = new StringBuilder(testedName);
removeChar.deleteCharAt(0);
// adds first character of testedName to the end of removeChar
String newString = removeChar.toString() + firstLetter;
// prints newString backwards
String reverseWord = new
StringBuffer(newString).reverse().toString();
// if statement - far simpler way to carry this task out than loops
// if statement to check if the words are the same
if (testedName.equals(reverseWord)) {
System.out.println(testedName + " is the same as " + reverseWord); }
else {
System.out.println(testedName + " is not the same as " + reverseWord); }
}
}
}
}
有人知道为什么程序每次检查一个单词时都不会返回到起始位置吗?不要这样比较字符串:
testedName != "quit"
这样做:
!testedName.equals("quit")
虽然这可能无法解决整个问题<代码>测试名称!=“退出”是错误的。使用
!testedName.equals(“quit”)
但我担心会出现无限循环,因为它在您的else
语句中,并且值不会在那里更改。@气垫船上满是鳗鱼-这本身并不是问题所在。因为循环的定位方式,它不会回圈。哇,这甚至不是被标记为。。。是的,一个错误是您将字符串与!=,这是行不通的,另一个错误是,当您需要将用户输入放入循环中时,您在循环之前获取用户输入。基本上,您错误地比较了字符串
,而您的else
循环从未得到一个新词,因此它将无限运行。好的,非常感谢,我更改了!=现在,仍然非常习惯循环,因此感谢您的帮助。更喜欢!“退出”。等于(testedName)
以避免可怕的NPE。