【问题标题】:Cant add space separated inputs using for loop无法使用 for 循环添加空格分隔的输入
【发布时间】:2017-04-12 10:20:13
【问题描述】:

我正在尝试使用 for 循环将空格分隔的输入添加到 hashmap,但我遇到了一些问题

    int G = s.nextInt();
    for (int i = 0; i < G; i++) {
        System.out.println("List girls qualities");     
        int j=1;
        String gir=s.next();
        String[] numbers = gir.split(" ");
        girlQualities=new HashMap<>();
        for (int x=0;x<numbers.length;x++)  
        {  
            int z=Integer.parseInt(numbers[x]);
            girlQualities.put(j,z); 
            j++;
        }
    }

当我使用 nextLine() 时,它显示 NumberFormatException 但即使现在它也无法正常工作。请帮我 我的目标是以这种方式添加数字

    3 
1 2 5 6 
1 2 3 4 5 
1 2 3 4 

【问题讨论】:

  • Java 有一个Scanner,它非常复杂,可以解析各种输入。
  • @WillemVanOnsem OP 提供的代码是否暗示他们正在使用名为s 的扫描仪?
  • 没有得到你@gifpif

标签: java for-loop nested


【解决方案1】:

那是因为 Scanner#nextInt 方法不会使用您输入的最后一个换行符,因此在下次调用 Scanner#nextLine 时会使用该换行符

试试

        int G = s.nextInt();
        s= new Scanner(System.in);

然后试试nextLine()方法

请参考Link

【讨论】:

  • 请您解释一下为什么会这样。 nextLine 应该返回当前行。我对上述情况有点困惑
  • 点击答案末尾给出的参考链接以获取详细的补偿..
猜你喜欢
  • 2012-04-19
  • 2020-06-17
  • 2012-01-31
  • 2015-08-17
  • 2019-01-31
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 2023-01-20
相关资源
最近更新 更多