2011-05-06 70 views
0

我遇到的問題是我必須輸入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); 
+1

對不起,這裏的問題究竟是什麼? – Liv 2011-05-06 11:46:47

回答

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; 

    //... 
} 
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>

0

Java中的控制檯輸入是行緩衝的。直到用戶輸入,你纔會得到任何東西。打空間,只是增加一個空間,你會得到的線。注意:點擊退格刪除一個你不會看到的字符。