我对循环有些新意,我需要在for循环之外插入一个while循环来计算空格,a,e,s和t。一旦用户键入短语,for循环将最后打印短语中空格,a,e,s和t的结果。我想创建一个while循环,允许你在输入“quit”时退出循环,并允许你键入一个新的短语,最终会得到更多的空格,a,e,s和t的结果。 。我已经尝试了while (phrase != "quit")
但它没有用。很抱歉,如果有任何混淆,但是当您看到输入和输出时,您可能会理解。这是代码:
import java.util.Scanner
public class Count
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int i = 0;
char ch; // an individual character in the string
String quit = "quit";
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
System.out.print ("Enter a sentence or phrase (quit to quit): ");
phrase = scan.nextLine(); // read input Scanner
int length = phrase.length(); // the length of the phrase
countBlank = 0;
int countA = 0;
int countE = 0;
int countS = 0;
int countT = 0;
for (i = 0; i < length; i++){
ch = phrase.charAt(i);
if (ch == (' '))
countBlank++;
switch (ch)
{
case 'a': case 'A': countA++; break;
case 'e': case 'E': countE++; break;
case 's': case 'S': countS++; break;
case 't': case 'T': countT++; break;
}
}
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
System.out.println ("Number of a's: " +countA);
System.out.println ("Number of e's: " +countE);
System.out.println ("Number of s's: " +countS);
System.out.println ("Number of t's: " +countT);
}
}
输出:
Character Counter
Enter a sentence or phrase (quit to quit): aest Aest aest
Number of blank spaces: 2
Number of a's: 3
Number of e's: 3
Number of s's: 3
Number of t's: 3