gpt4 book ai didi

java - 无限循环,不会以while循环结束

转载 作者:行者123 更新时间:2023-12-01 16:39:41 24 4
gpt4 key购买 nike

好吧,我已经编写了这个程序,它将计算某些字母和空格,我想要它做的是让用户继续输入短语,并且它继续循环,直到用户输入 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=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 ();

}
}
}

最佳答案

在 while 循环中,您永远不会阅读下一行。您需要添加

phrase = scan.nextLine();

在“for”循环之后,但仍在“while”循环内。否则,短语将始终是您读入的第一个内容。

关于java - 无限循环,不会以while循环结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5224930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com