如何让这个输出更容易?

时间:2011-05-06 11:33:21

标签: java

我遇到的问题是我必须输入50个整数,当我点击空格时它将无法识别数字,当我点击输入时,我的输出框非常长,只有1位#的

static final int MAX = 50;
public static void main(String[] args)
{
    int index;
    int check;
    int infants = 0, children = 0, teens = 0, adults = 0;
    System.out.println("This program will count the number of people "
                        + "and how many of that age group cameto the college fair.");
    System.out.println("**********************************************************");
    System.out.println("Please enter the integer value data:");
    int [] peopleTypes = new int[MAX];

    Scanner keyboard = new Scanner(System.in);

    for(index=0; index<MAX; index++)
        {
            peopleTypes[index] = keyboard.nextInt();
            if(peopleTypes[index] == 1)
                infants = infants + 1;
            if(peopleTypes[index] == 2)
                children = children + 1;
            if(peopleTypes[index] == 3)
                teens = teens + 1;
            if(peopleTypes[index] == 4)
                adults = adults + 1;
            else
                index = index-1;
            System.out.print("");
        }

    System.out.println("The number of infants that were at the college fair was: " + infants);
    System.out.println("The number of children that were at the college fair was: " + children);
    System.out.println("The number of teenagers that were at the college fair was: " + teens);
    System.out.println("The number of adults that were at the college fair was: " + adults);

3 个答案:

答案 0 :(得分:1)

尝试使用它:

public class ScannerDelimiter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner("12, 42, 78, 99, 42");
        scanner.useDelimiter("\\s*,\\s*");
        while (scanner.hasNextInt()) {
            System.out.println(scanner.nextInt());
        }
    }
} /* Output:
12
42
78
99
42

在这种情况下,分隔符是

<any number of spaces or tabs>,<any number of spaces or tabs>

答案 1 :(得分:0)

您可以将输入作为字符串读取并尝试解析它:

String s = "";
int i = 0;
for (index = 0; index < MAX; index++) {
    s = keyboard.next();
    try {
        i = Integer.valueOf(s.trim());
    } catch (NumberFormatException nfe) {
        // log exception if needed
        System.out.println(s + " is not a valid integer.");
        continue;
    }

    // do the rest
    peopleTypes[index] = i;

    //...
}

答案 2 :(得分:0)

Java中的控制台输入是行缓冲的。在用户点击进入之前你不会得到任何东西。击中空间,只需为您将获得的线条添加空间。注意:点击退格键会删除您也看不到的字符。