我尝试使用此代码,但是每次运行并键入quit时,它都会打印出结果,就好像它应该是一个单词而不是结束循环的触发器,然后循环结束。我只是尝试在if if语句中放入一个单词if quit,它将结束整个程序,但是我无法摆脱单词不等于“ quit”的do while循环。这是代码。
do
{
System.out.println("Enter a word and I will see if, when the first letter is made the last" + '\n' + "and this word is spelled backwards, is the original word. Type quit to end: ");
word = keyboard.next().toLowerCase();
String newWord = word.substring(1) + word.charAt(0);
String reverse = "";
for(int wordLength = newWord.length() - 1; wordLength >= 0; wordLength--)
{
reverse = reverse + newWord.charAt(wordLength);
}
if (word.equals(reverse)) {
System.out.println("You have entered " + word + ". Does this word with it's first letter made the last then spelled in reverse become the original word? Yes!");
} else {
System.out.println("You have entered " + word + ". Does this word with it's first letter made the last then spelled in reverse become the original word? No");
}
}while (!word.equals("quit"));
一如既往,感谢您的帮助!
do while循环仅在到达循环末尾时检查条件。因此,代码中发生的事情是,当将word设置为“退出”时,它下面的代码仍将运行直到到达循环结束。
要实现您想做的尝试,
do
{
System.out.println("Enter a word and I will see if, when the first letter is made the last" + '\n' + "and this word is spelled backwards, is the original word. Type quit to end: ");
word = keyboard.next().toLowerCase();
if(word.equals("quit")){ break; }
String newWord = word.substring(1) + word.charAt(0);
String reverse = "";
for(int wordLength = newWord.length() - 1; wordLength >= 0; wordLength--)
{
reverse = reverse + newWord.charAt(wordLength);
}
if (word.equals(reverse)) {
System.out.println("You have entered " + word + ". Does this word with it's first letter made the last then spelled in reverse become the original word? Yes!");
} else {
System.out.println("You have entered " + word + ". Does this word with it's first letter made the last then spelled in reverse become the original word? No");
}
}while (true);
这将导致for循环在输入退出时在输出文本之前停止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句