【问题标题】:Character Counter with a switch statement java带有switch语句java的字符计数器
【发布时间】:2012-11-16 00:29:39
【问题描述】:

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

我还必须使用一个开关来增加每个的计数。由于这是我第一次在程序中使用 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");
}
}

【问题讨论】:

    标签: java character switch-statement counter


    【解决方案1】:

    你永远不想写这个:

    inx = inx ++;
    

    你的意思很简单

    inx++;
    

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

    【讨论】:

    • inx = inx++之所以出错,是因为inx++的定义。它有增加 inx 的副作用,但它的值,将分配给 inx 的值,是旧值。
    • 啊,一个明显的错误!几个星期以来,我没有在任何 java 上工作过。非常感谢,会试一试!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2019-08-26
    • 2012-10-24
    相关资源
    最近更新 更多