【问题标题】:Reading from text file into array but no such element exception occuring?从文本文件读取到数组但没有发生这样的元素异常?
【发布时间】:2017-09-02 00:59:38
【问题描述】:

我是计算机科学的初学者,尝试将文本文件中的整数放入数组时遇到了一些麻烦。文本文件中有 7 行整数,每行有 3 个整数,用空格隔开,例如:

0 15 20
100 25 96
85 42 15
52 63 47
85 44 98 
41 55 74
85 74 15

我应该将每一行中的三个数字放入三个不同的数组中,这样一个数组将包含第一个数字,第二个数组将包含第二个数字,第三个数组将包含第三个数字,所有这些都来自同一行。 我的代码在下面,但是当它运行它时,我得到了一个没有这样的元素异常,当我打印第一个数组时,它显示了存储在数组第一个位置的第一个数字,但是其余的数字是第二个数字每一行。循环中发生了什么?:(我将不胜感激任何类型的解释。

    import java.io.*;
    import java.util.Scanner;
    import java.util.Arrays;
    public class Trying{
    public static void main(String [] args){
    Scanner s=null;
    int [] a= new int [7];
    int [] b= new int [7];
    int [] c= new int [7];
    int i=0;
    try{
      s= new Scanner(new File("input.txt"));
      while(s.hasNextLine()){
        String line=s.nextLine();
        Scanner cal= new Scanner(line);
        a[i]=cal.nextInt();
        b[i]=cal.nextInt();
        c[i]=cal.nextInt();
        i++; 
      }
    }
    catch(Exception eee){
      eee.printStackTrace();
    }
    System.out.println(Arrays.toString(a));
  }
}

【问题讨论】:

    标签: arrays file exception text integer


    【解决方案1】:

    您应该替换“c[i]=s.nextInt();”使用“c[i]=cal.nextInt();”。我认为您错误地使用了 s 扫描仪对象而不是 cal 扫描仪对象。

    你也可以使用 String.split() 方法来达到你的目的。 而不是使用

    String line=s.nextLine();
        Scanner cal= new Scanner(line);
        a[i]=cal.nextInt();
        b[i]=cal.nextInt();
        c[i]=s.nextInt();
    

    你可以试试这个:

    String[] lines=s.nextLine().split(" ");
        a[i]=Integer.parseInt(lines[0]);
        b[i]=Integer.parseInt(lines[1]);
        c[i]=Integer.parseInt(lines[2]);
    

    【讨论】:

    • 谢谢!我实际上并没有注意到我调用的是 s 扫描仪而不是 cal 扫描仪,但在这里输入它有点错误:) 我会试试你说的,所以每当我扫描一行时,我都必须把它分开摆脱空间?对于这个问题,我很抱歉,正如我所说,我才刚刚开始,也没有其他人可以问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多