【问题标题】:Trouble with passing a value into loop将值传递到循环中的问题
【发布时间】:2019-03-31 23:04:53
【问题描述】:

如果文本文件由数字行组成,则下面的代码运行得非常好,但是一旦到达例如“我是 40”的行,它就会跳过它而不是将 40 放入数组中。

Scanner inFile = null;
    File file = null;
    String filePath = (JOptionPane.showInputDialog("Please enter a file path"));
    int size = 0;
    int[] result = new int[10];


    try {
        file = new File(filePath);
        inFile = new Scanner(file);
        int skippedCounter = 0;

        for(int i = 0; inFile.hasNext(); i++){
            if(inFile.hasNextInt())
                result[i] = inFile.nextInt();
            else{
                String strOut = "";
                String data = inFile.next();

                for(int j = 0; j <= data.length() - 1; j++){
                    if(!Character.isLetter(data.charAt(j))){
                        strOut += data.charAt(j);
                    }
                    else
                        skippedCounter++;
                }
                result[i] = Integer.parseInt(strOut);
            }
        }
    }

【问题讨论】:

  • 您是否尝试调试过您的代码?

标签: java arrays io


【解决方案1】:

next() 会给你下一个令牌而不是下一行。所以变量i 可能会超过十点。如果您没有空捕获,您会意识到这一点:您的数组超出范围

解决方案:

不要使用结果数组,使用结果列表,并在有其他结果时追加到其末尾

注意:

另一个可能发生的隐藏异常是您的 parseInt 由于非数字数据而失败。所以不要把所有东西都包装在一个巨大的 try/catch 中,它只会让调试变得更加困难!

【讨论】:

  • 这行得通,但现在我遇到了一个问题,当我将数组列表打印到数组时,我似乎无法摆脱一些空元素
【解决方案2】:

我建议您只使用一次 nextInt 函数来保留请求的值,然后在需要时使用该变量。我认为 nextInt 函数每次上诉时都会移动到下一个 int 。

【讨论】:

    【解决方案3】:

    以下

    result[i] = Integer.parseInt(strOut)
    

    在尝试处理任何字母时将导致NumberFormatException。由于strOut 导致空字符串""

    您必须在尝试解析之前检查空字符串

    if (!strOut.isEmpty()) {
        result[i] = Integer.parseInt(strOut);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2020-02-19
      • 1970-01-01
      • 2020-10-01
      • 2019-02-05
      • 2019-06-28
      • 1970-01-01
      相关资源
      最近更新 更多