尝试使用多个1D数组,同时在Java中读取文件
我是一名新的java程序员,目前正开始学习如何读取文件。我正在进行一项活动,需要在一个单独的方法中将文本文件中的数字读入整数数组,然后在main方法中添加三个数组中的每个数组的值 以下是我到目前为止的情况:尝试使用多个1D数组,同时在Java中读取文件,java,arrays,file,Java,Arrays,File,我是一名新的java程序员,目前正开始学习如何读取文件。我正在进行一项活动,需要在一个单独的方法中将文本文件中的数字读入整数数组,然后在main方法中添加三个数组中的每个数组的值 以下是我到目前为止的情况: import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class FileToArrays{ public static void main(Strin
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileToArrays{
public static void main(String[] args){
int[] b = new int [7];
int[] l = new int [7];
int[] d = new int [7];
readFile(b, l, d);
System.out.println("Sum of First Numbers: "+(b[0]+l[0]+d[0]));
System.out.println("Sum of Second Numbers: "+(b[1]+l[1]+d[1]));
System.out.println("Sum of Third Numbers: "+(b[2]+l[2]+d[2]));
System.out.println("Sum of Fourth Numbers: "+(b[3]+l[3]+d[3]));
System.out.println("Sum of Fifth Numbers: "+(b[4]+l[4]+d[4]));
System.out.println("Sum of Sixth Numbers: "+(b[5]+l[5]+d[5]));
System.out.println("Sum of Seventh Numbers: "+(b[6]+l[6]+d[6]));
System.out.println("");
}
static void readFile(int[] b, int[] l, int[] d){
try{
Scanner scnr = new Scanner(new File("Input.txt"));
int day = 0;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
String [] words = line.split(" ");
b[day] = Integer.parseInt(words [0]);
l[day] = Integer.parseInt(words [1]);
d[day] = Integer.parseInt(words [2]);
day++;
}
scnr.close();
}catch(FileNotFoundException e){
System.out.println("Unable To Find File");
}
}
}
我在数组中读取的数字的文本文件Input.txt的格式如下:
800 1000 800
450 845 1200
1800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
程序编译时没有错误,但当我尝试运行它时,三个数组中的每个值都显示为0
我觉得问题可能是一些琐碎的事情,比如参数和格式错误,也可能是我把文件读入数组的方式弄乱了
尽管如此,任何关于我在哪里搞砸了的见解或关于如何在未来完成类似任务的建议都将不胜感激
谢谢您的时间。为输入文件提供绝对路径,如C:/Users/input.txt,它将正常工作 欢迎杰克, 代码看起来不错,但对于所提供的文件/数据来说效果不佳。如果你仔细看,数字之间有不止一个空格。 您正在对每个空格字符串[]words=line.split上的行进行夹板分割,这将为您提供比预期更大的数组 对于此类任务,更好的方法是使用Scanner.next,它将忽略所有空格 尝试用以下内容替换代码:
while(scnr.hasNext()){
b[day] = scnr.nextInt();
l[day] = scnr.nextInt();
d[day] = scnr.nextInt();
day++;
}
它对我有效,问题可能是输入文件的位置,请给出绝对路径。比如C:/Users/input.txt