只要用户没有结束“退出”,我在编写代码以进行 while 循环询问用户输入时遇到问题。当我运行代码时,它只会生成第一个提示问题“输入句子或短语:”,然后在输入短语后它不会计算 while 语句。有谁知道我做错了什么?
问题是:“让程序让用户继续输入短语而不是每次都重新启动它会很好。为此,我们需要围绕当前代码的另一个循环。也就是说,当前循环将嵌套在里面新循环。添加一个外部while循环,只要用户不输入短语quit,它将继续执行。修改提示以告诉用户输入短语或退出退出。注意所有初始化counts 应该在 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, countE, countS, countT; // variables for counting the number of each letter
scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ("(to quit the program, enter 'quit' when prompted for a phrase)");
System.out.println ();
// Creates a while loop to continue to run the program until the user
// terminates it by entering 'quit' into the string prompt.
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
while (phrase != "quit");
{
length = phrase.length();
// Initialize counts
countBlank = 0;
countA = 0;
countE = 0;
countS = 0;
countT = 0;
// a for loop to go through the string character by character
// and count the blank spaces
for (int i = 0; i < length ; i++)
{
ch = phrase.charAt(i);
switch (ch)
{
case 'a': // Puts 'a' in for variable ch
case 'A': countA++; // Puts 'A' in for variable ch and increments countA by 1 each time
break; // one of the variables exists in the phrase
case 'e': // puts 'e' in for variable ch
case 'E': countE++; // ... etc.
break;
case 's':
case 'S': countS++;
break;
case 't':
case 'T': countT++;
break;
case ' ': countBlank++;
break;
}
}
// Print the results
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);
System.out.println ();
}
}
}