2016-03-28 68 views
-2

我想裏面讀取環路與掃描器類兩個變量然後將它們保存在收集地圖代碼如下:我怎麼能讀循環java的兩個輸入

public class Example{ 

public static void main(String args[]){ 

    Map<String,Integer> mapSub = new HashMap<String,Integer>(); 
     for (int i=0;i<nbSubnet;i++){ 
     System.out.println("Enter name of the subnet "+i+" : "); 
     String nameSubnet = scanner.nextLine(); 
     System.out.println("Enter the size of the subnet "+i+" : "); 
     int sizeSubnet = scanner.nextInt(); 

     mapSub.put(nameSubnet, sizeSubnet); 
    } 
    } 
} 

但在運行後,我得到這個exeption驗證碼:

Enter name of the subnet 0 : 
Enter the size of the subnet 0 : 
IT 
Exception in thread "main" java.util.InputMismatchException 
at java.util.Scanner.throwFor(Unknown Source) 
at java.util.Scanner.next(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at view.Main.main(Main.java:60) 

任何幫助將是巨大的感謝

+4

據我所知,'IT'不是'int' – Hackerdarshi

+0

我給它的字符串「IT」作爲名字,是我從代碼做期待,請問串首先,然後要求的整數大小 – azdoud

+0

我認爲這將有助於http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods – RubioRic

回答

0

您需要驗證您的輸入,以確保你得到你所期望的類型。 IT不是int,所以當然int sizeSubnet = scanner.nextInt();將會失敗。

至少,try/catch是一個好主意。

int sizeSubnet; 
try{ 
    sizeSubnet = scanner.nextInt(); 
} catch() { 
    sizeSubnet = 0; 
} 

如果用戶希望ITnameSubnet,那麼你就需要make sure the scanner waits for the input一個額外scanner.nextLine();

+0

球員我想先分配nameSubnet由String nameSubnet = scanner.nextLine();這就是爲什麼我給它字符串「IT」 – azdoud

+0

@azdoudyoussef那麼你應該交換輸入的地方。 –

+0

@azdoudyoussef這就是爲什麼我更新了答案 - 閱讀鏈接以瞭解爲什麼需要添加額外的行。發生的事情是,你沒有等待用戶的輸入,所以你輸入的第一個東西不會被當作名字來讀取,而是被讀作大小。 – senschen

0

這裏異常的原因是scanner.nextInt();返回int,並在運行時要傳遞IT這是java.lang.String類型。 和int類型的變量不能存儲String

+0

當你第二次輸入輸入時,這個異常是否升起? –

+0

當然,這裏有點明顯。 –

+0

當您嘗試從控制檯接收字符串輸入時,此問題經常會增加。因爲字符串終止符號'\ n'仍保留在緩衝區中。所以當控制器第二次來時,編譯器認爲'\ n'是給定的輸入由用戶,它需要'\ n'作爲輸入,並不等待用戶輸入。 嘗試在進行第二次輸入之前刷新緩衝區,並且不會再次遇到此問題。 –

相關問題