好的,所以我写了这个程序,它将计算一定的字母和空格,我想要它做的是让用户继续输入短语,它继续循环,直到用户进入退出终止.我很难看到在哪里放置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=0,countE=0,countS=0,countT=0;
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase or enter (Quit) to quit: ");
phrase = scan.nextLine();
while(!phrase.equalsIgnoreCase ("Quit"))
{
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
switch(ch=phrase.charAt(i))
{
case 'a':
case 'A': countA++;
break;
case 'e':
case 'E': countE++;
break;
case 's':
case 'S': countS++;
break;
case 't':
case 'T': countT++;
break;
}
}
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ("Number of a: " + countA);
System.out.println ("Number of e: " + countE);
System.out.println ("Number of s: " + countS);
System.out.println ("Number of t: " + countT);
System.out.println ();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在while循环中,你永远不会读下一行.你需要添加
phrase = scan.nextLine();
Run Code Online (Sandbox Code Playgroud)
'for'循环后,但仍然在'while'循环内.否则,短语将始终是您阅读的第一件事.