从文本文件读入数组,但没有发生此类元素异常?
问题描述:
我是计算机科学的初学者,在尝试将整数从文本文件放入数组时遇到了一些麻烦。有在文本文件中七行的整数,并且每个线具有由空格分隔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));
}
}
答
,就应该替换 “C [1] = s.nextInt();”?用“C [1] = 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]);
谢谢!我其实并没有注意到我正在调用扫描仪而不是校准扫描仪,但在这里输入它有点不对劲:)我会尝试你所说的,所以每当我扫描一行时,我必须将它分开摆脱空间?我为这个问题感到抱歉,正如我所说的,我几乎没有开始这个问题,也没有人会问。 – xValentinax