2014-04-16 51 views
1

我有一個應該將信息存儲到對象數組中的循環,但由於某種原因,它總是跳過第一個輸入。鍵盤輸入循環時出錯

public class GerbilData { 
public static void main(String[] args){ 
    Scanner keyboard = new Scanner(System.in); 

    System.out.println("How many different food items do the gerbils eat?"); 

    int n1 = keyboard.nextInt(); 
    Food[] gerbilFood = new Food[n1]; 
    String temp; 
    int temp2; 
    int count = 1; 

    for (int a = 0; a < n1; a++){ 
     gerbilFood[a] = new Food(); 
    } 

    int j = 0; 
    while (j < n1){ 
     System.out.println("Name of food item " + count + ":"); 
     temp = keyboard.nextLine(); 
     gerbilFood[j].setName(temp); 
     count++; 
     j++; 
    } 

回答

1

keyboard.nextInt()只讀取鍵盤上的整數,而不是讀取返回字符。所以,當你第一次打電話給keyboard.nextLine()時,你會得到getInt()\n

試試這個:

int n1 = keyboard.nextInt(); 
keyboard.nextLine(); 
+0

太感謝你了! – user3543032

+0

很高興幫助!如果您發現它有幫助,請記住接受答案。 – slaadvak