该程序的作用是获取用户输入的单词并以 pig 拉丁语形式返回它们。翻译循环将继续,直到用户输入“退出”。我的问题是,当程序执行并翻译这些单词时,输入“退出”一词后,它会翻译“退出”,这是我不希望它这样做的。我知道它在完成之前翻译“退出”的原因是它是一个 do while 循环,但我坚持如何创建一个起作用的 while 循环。我将如何更改程序,以便“退出”终止循环并且不被翻译? 例子: 词语: 退出 伊特盖伊
import java.util.Scanner;
public static void main(String[] args) {
String word;
Scanner input = new Scanner(System.in);
do {
System.out.print("Word: ");
word = input.next();
System.out.println(pigLatinWord(word));
System.out.println();
} while (!word.equalsIgnoreCase("quit"));
System.out.println("Translation complete");
}
// --------------------------------------------------------
// Convert one word to pig Latin.
public static String pigLatinWord(String s) {
String pigWord;
if (isVowel(s.charAt(0))) {
pigWord = s + "-way";
} else if (s.startsWith("th") || s.startsWith("Th")) { // or
// (s.toUpperCase().startsWith("TH"))
pigWord = s.substring(2) + "-" + s.substring(0, 2) + "ay";
} else {
pigWord = s.substring(1) + "-" + s.charAt(0) + "ay";
}
return pigWord;
}
// ---------------------------------------------
// Determines whether c is a vowel character
public static boolean isVowel(char c) {
String vowels = "aeiouAEIOU";
return (vowels.indexOf(c) >= 0); // when index of c in vowels is not -1,
// c is a vowel
}
}
最佳答案
在有机会检查该单词是否等于“quit”之前,您正在执行pigLatinWord(word)
。您可以这样更改循环:
do {
System.out.print("Word: ");
word = input.next();
if( "quit".equalsIgnoreCase(word) )
break;
System.out.println(pigLatinWord(word));
System.out.println();
} while (true);
关于Java循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22923798/