所以我创建了这个程序来操作用户提供的单词作为输入,通过将第一个字符移动到单词的结尾,然后将单词的其余部分向后拼写,然后检查原始单词和新词是一样的。它被设计为运行直到用户输入单词“quit”作为所选单词。我已经设法让大部分代码都能正常工作,除了在检查前一个代码之后循环回去询问用户一个新单词,它只是继续运行。我目前得到的代码如下:
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); }
}
}
}
}
有没有人知道为什么程序每次检查一个单词时都不会循环回到开头?
答案 0 :(得分:0)
不要比较这样的字符串:
testedName != "quit"
这样做:
!testedName.equals("quit")