【发布时间】:2016-10-20 02:18:04
【问题描述】:
我是循环的新手,我已经编写了一个 for 循环,提示用户输入一个短语,for 循环打印出有多少空格,a's,e's ,s's 和 t's。我需要做一个while循环,允许用户输入“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;
//I am not sure how to set up the start of the while loop
//while (!phrase.equals("quit")){
//while (phrase != "quit"){
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
Number of blank spaces: 1
Number of a's: 2
Number of e's: 2
Number of s's: 2
Number of t's: 2
【问题讨论】:
标签: java loops while-loop switch-statement