2017-04-22 27 views
1

在這裏,我試圖從用戶獲得兩個鍵盤輸入到一個單一的數組索引位置。如何使用循環將鍵盤輸入值放入數組中?

/* 
    * To change this license header, choose License Headers in Project Properties. 
    * To change this template file, choose Tools | Templates 
    * and open the template in the editor. 
    */ 
    package tour; 

    import java.util.Scanner; 
    import tour.City; 

    /** 
    * 
    * @author dp 
    */ 
    public class Tour { 

     /** 
     * @param args the command line arguments 
     */ 
     public static void main(String[] args) { 
      // TODO code application logic here 

      City[] city = new City[9]; 

      Scanner in = new Scanner(System.in); 

      for(int i=0;i<city.length;i++) 
      { 
       int no = in.nextInt(); 
       String name = in.nextLine(); 

       city[i]= new City(no,name); 
      } 
     } 

    } 

當我運行此代碼時,它會給我以下例外。 enter image description here

我對java很陌生,不知道如何解決這個問題。

回答

3

由於12NY都在不同的線路,當你做

String name = in.nextLine(); 

,你得到的回覆是空的String。這是因爲Scanner的「讀取點」位於12之後,但位於其後面的行尾標記之前。

您可以通過添加另一個nextLine,並放棄其結果是解決這個問題:

in.nextLine(); // Skip to end-of-line after the number 
String name = in.nextLine(); 
+0

問題解決了。非常感謝! – Punya

0

您正在使用nextInt()nextLine()方法來讀取用戶輸入,這些方法讀取next可用的令牌,所以這是怎樣的現有代碼工作:

  • 它讀取使用nextInt()一個數並分配給no
  • 用戶然後點擊return和控制讀取一個空行(作爲下一行是空的),並將其分配到name
  • City對象獲取與作爲12no作爲<empty_string>創建name。爲了循環啓動,它是第二次執行。
  • 到了這個時候,用戶鍵入NY和點擊返回
  • 正如預期(通過調用nextInt())令牌是一個int,它失敗並拋出異常。

如果你想控制讀取分別在兩個輸入(和等待,直到用戶點擊返回),使用方法:

int no = Integer.parseInt(in.next()); 
String name = in.next(); 
0

只需要讀INT到最後一行的

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package tour; 

import java.util.Scanner; 
import tour.City; 

/** 
* 
* @author dp 
*/ 
public class Tour { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     // TODO code application logic here 

     City[] city = new City[9]; 

     Scanner in = new Scanner(System.in); 

     for(int i=0;i<city.length;i++) 
     { 
      int no = in.nextInt(); 
      in.nextLine();//read to the end of line 
      String name = in.nextLine(); 

      city[i]= new City(no,name); 
     } 
    } 

}