开发者

How can i make this output easier?

The problem I am having is I have to input 50 integers, and when I hit space it won't recognize the number and when I hit enter then my output box is very very long for just 1 digit #'s

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);


Try to use this:

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

In this case the delimiter is

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


You could read your input as a String and try to parse it:

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;

    //...
}


Console input in Java is line buffered. You won't get anything until the user hits enter. Hitting space, just adds a space to the line you will get. Note: hitting backspace deletes a character which you won't see either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜