2016-03-28 69 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'作为输入,并不等待用户输入。 尝试在进行第二次输入之前刷新缓冲区,并且不会再次遇到此问题。 –

相关问题