ユーザーが「終了」しない限り、ユーザー入力を要求する while ループを作成するコードの作成に問題があります。コードを実行すると、最初のプロンプトの質問「文またはフレーズを入力してください:」しか生成されず、フレーズを入力した後、while ステートメントは計算されません。私が間違っていることを誰かが知っていますか?
質問は次のとおりです。「プログラムを毎回再起動するのではなく、ユーザーがフレーズを入力し続けることができるようにするとよいでしょう。これを行うには、現在のコードを囲む別のループが必要です。つまり、現在のループは内側にネストされます。新しいループ. ユーザーが句を入力しない限り実行を続ける外側の while ループを追加します. quit.カウントは 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 ();
}
}
}