我想知道如何讓程序結束重複,如果用戶確實迴應1。我是否需要重新組織它,以便它是if語句的一部分?所以我在這裏有這個代碼,它計算給定短語中的元音。我試圖讓它重複,如果用戶說是的
Scanner input = new Scanner(System.in);
System.out.println("Count Vowels \n============");
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int answer;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() + Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
if (answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
} else {
System.out.println("Have a nice day");
}
不清除'Scanner'緩衝也許? – Azar 2014-11-08 02:58:25
你應該看看'do/while'循環是什麼以及它們是如何工作的。然後你可以在用戶輸入'1'的時候重複你的程序。 – Tom 2014-11-08 02:58:30
您可以使用while循環...只要用戶輸入1,程序就會繼續,否則程序將跳出循環。 – 2014-11-08 03:02:52