好吧,所以我寫了這個程序,它將計算某些字母和空格,我希望它執行的操作是讓用戶不斷輸入短語,並繼續循環直到用戶輸入quit終止。我無法看到放置while循環的位置。我知道我應該在while循環下嵌套所有的循環,當我這樣做時,程序進入無限循環。無限循環,不會以while循環結束
import java.util.Scanner;
public class Count
{
public static void main (String[] args)
{
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
int countA=0,countE=0,countS=0,countT=0;
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println();
System.out.println ("Character Counter");
System.out.println();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase or enter (Quit) to quit: ");
phrase = scan.nextLine();
while(!phrase.equalsIgnoreCase ("Quit"))
{
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
switch(ch=phrase.charAt(i))
{
case 'a':
case 'A': countA++;
break;
case 'e':
case 'E': countE++;
break;
case 's':
case 'S': countS++;
break;
case 't':
case 'T': countT++;
break;
}
}
// Print the results
System.out.println();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ("Number of a: " + countA);
System.out.println ("Number of e: " + countE);
System.out.println ("Number of s: " + countS);
System.out.println ("Number of t: " + countT);
System.out.println();
}
}
}
首先,採取「退出」,而不是「退出」,並且您應該使用ToLower()以確保tolower之後的「quItE」=「quit」。 – 2011-03-07 20:39:30
不要在循環內「初始化」某些東西,它會在每個循環中重新初始化 – 2011-03-07 20:40:12