簡體   English   中英

如何使此輸出更容易?

[英]How can i make this output easier?

我遇到的問題是我必須輸入50個整數,當我按空格鍵時將無法識別該數字,當我按Enter鍵時,我的輸出框會非常長,只有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);

嘗試使用此:

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>

您可以將輸入讀取為字符串,然后嘗試解析它:

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;

    //...
}

Java中的控制台輸入是行緩沖的。 在用戶點擊Enter之前,您將一無所獲。 擊中空間,只需在要獲得的行上添加一個空間。 注意:按退格鍵將刪除一個您也看不到的字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM