如何读取循环java中的两个输入

eeq64g8w  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(498)

我想用scanner类读入for循环中的两个变量,然后将它们保存在一个集合中。代码如下:

  1. public class Example{
  2. public static void main(String args[]){
  3. Map<String,Integer> mapSub = new HashMap<String,Integer>();
  4. for (int i=0;i<nbSubnet;i++){
  5. System.out.println("Enter name of the subnet "+i+" : ");
  6. String nameSubnet = scanner.nextLine();
  7. System.out.println("Enter the size of the subnet "+i+" : ");
  8. int sizeSubnet = scanner.nextInt();
  9. mapSub.put(nameSubnet, sizeSubnet);
  10. }
  11. }
  12. }

但我在运行代码之后得到了这个例外:

  1. Enter name of the subnet 0 :
  2. Enter the size of the subnet 0 :
  3. IT
  4. Exception in thread "main" java.util.InputMismatchException
  5. at java.util.Scanner.throwFor(Unknown Source)
  6. at java.util.Scanner.next(Unknown Source)
  7. at java.util.Scanner.nextInt(Unknown Source)
  8. at java.util.Scanner.nextInt(Unknown Source)
  9. at view.Main.main(Main.java:60)

任何帮助都很好谢谢

mtb9vblg

mtb9vblg1#

你需要验证你的输入,以确保你得到你想要的类型。 IT 不是一个 int ,那当然 int sizeSubnet = scanner.nextInt(); 会失败的。
至少,试一试是个好主意。

  1. int sizeSubnet;
  2. try{
  3. sizeSubnet = scanner.nextInt();
  4. } catch () {
  5. sizeSubnet = 0;
  6. }

如果你期待的话 IT 应该是 nameSubnet ,然后您需要确保扫描仪等待带有额外 scanner.nextLine(); .

1cklez4t

1cklez4t2#

例外的原因是 scanner.nextInt(); 返回一个 int ,并在运行时传递 java.lang.String . 和类型的变量 int 无法存储 String

相关问题