2

我正在编写一个字符计数器程序,它读取一行文本并计算元音、辅音、空格和标点符号的数量。

我还必须使用一个开关来增加每个的计数。由于这是我第一次在程序中使用 switch 语句,我不确定我是否在循环中正确使用它。

据我所知,问题在于它编译时的循环,但是当它运行时,它挂在终端中,所以我假设循环没有正确终止。

我知道我计算字符的方法非常基本,但这是按照说明进行的。

谢谢

import java.util.Scanner;
import java.io.*;

public class CharacterCounter2
{
public static void main(String args[])
{

Scanner scan = new Scanner(System.in);
String line = new String(scan.nextLine());

String cons = new String ("bcdfghjklmnpqrstvwxyz");
String vowels = new String ("aeiou");
String space = new String (" ");
String punct = new String(",.;:");

int consCount = 0, vowelCount = 0, spaceCount = 0, pCount = 0, inx = 0;
char ch = line.charAt(inx);

while (inx <= line.length()-1)

{
if (cons.indexOf(line.charAt(inx)) != -1)
ch = 'C';
else 
if (vowels.indexOf(line.charAt(inx)) != -1)
ch = 'V';
else
if(line.equals(space))
ch = 'S';
if (punct.indexOf(line.charAt(inx)) != -1)
ch = 'P';

switch (ch)
{
case 'C':
consCount += 1;
break;

case 'V':
vowelCount += 1;
break;

case 'S':
spaceCount += 1;
break;

case 'P':
pCount += 1;

default:
break;

}

inx = inx ++;
ch = line.charAt(inx);
}



System.out.println("contains" +consCount+" consonants, "+vowelCount+" vowels, " + spaceCount+" spaces" + pCount + "punctuation");
}
}
4

1 回答 1

3

你永远不想这样写:

inx = inx ++;

你的意思很简单

inx++;

这至少应该让循环终止,否则我认为它可能会起作用,除非你的空间计数逻辑是错误的。

于 2012-11-16T00:32:23.107 回答