因此,当用户输入quit时,我的程序不会停止,并且每次运行时变量都会不断加起来,当我只有一个人在一次运行中计算字符时,然后计算下一个输入。所以程序会对字符串中的特定字符进行计数,但是无论第一次和第一次我希望用户可以选择停止和结束程序,我都希望它能够计算
public class Count {
public static void main (String[] args) {
String phrase; // a string of characters
int blankCount; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scanner = new Scanner(System.in);
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
System.out.print ("Enter a sentence or phrase: ");
blankCount = 0;
int aCount = 0;
int eCount = 0;
int sCount = 0;
int tCount = 0;
int timesRan = 0;
do {
phrase = scanner.nextLine();
length = phrase.length();
for(int i=0; i<length; i++){
switch(phrase.charAt(i)){
case ' ':
blankCount++;
break;
case 'a':
aCount++;
break;
case 'A':
aCount++;
break;
case 'e':
eCount++;
break;
case 'E':
eCount++;
break;
case 's':
sCount++;
break;
case 'S':
sCount++;
break;
case 't':
tCount++;
break;
case 'T':
tCount++;
break;
}
timesRan++;
}
System.out.println ("Number of space characters: " + blankCount);
System.out.println ("Number of a's: " + aCount);
System.out.println ("Number of e's: " + eCount);
System.out.println ("Number of s's: " + sCount);
System.out.println ("Number of t's: " + tCount);
System.out.print("Enter a phrase or enter quit, to quit: ");
} while(phrase != "quit" && timesRan >= 0);
}
}
答案 0 :(得分:2)
尝试在switch语句中添加默认大小写。而不是与!=进行比较,在while中尝试.equals方法。因此,while部分中的代码应为:while (phrase.equals("quit")==false && timesRan >= 0)