我是循环的新手,我编写了一个for循环,提示用户输入一个短语,for循环打印出多少空格,a,e,s和t。我需要创建一个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
答案 0 :(得分:4)
您走在正确的轨道上,但是一旦完成该过程,您确实需要再次阅读该短语以使while循环工作。否则,它将是无限循环。 我做了一些改变:
while (!phrase.equals("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);
phrase =scan.nextLine(); //read next phrase from user to continue.
}
答案 1 :(得分:1)
在phrase = scan.nextLine();
之后使用此功能
if(phrase.equalsIgnoreCase("quit")){
return;
}