我需要帮助完成我必须为我的班级做的作业。我才刚刚开始使用 Java,所以我对它很陌生。我需要编写一个代码来扫描文本文件中的数字,然后计算它们并创建一些平均值。我使用 for 循环来扫描文件,但我不知道如何扫描它,所以它每隔三行就跳过一次。我需要每一列文本而不是每一行。文本文件包含 3 列和 7 行。
public static void main(String [] args){
readData("Sample.in");
}
static void readData(String fileName){
try{
int[] breakfast= new int[7];
int[] lunch=new int[7];
int[] dinner= new int[7];
File input = new File(fileName); // Creates Scanner to read line from the text file
Scanner scanLine = new Scanner(input); // Reads entire line from the file
String line= scanLine.nextLine(); // To read numbers from the Line buffer
Scanner scanNumber = new Scanner(line); // to read three numbers from the line buffer
for(int meal =0; meal<3; meal++){ // Checks whether the number is present in the line
if(scanNumber.hasNextInt()){ // read number from the line buffer and store it in the calories variable
int calories = scanNumber.nextInt();
System.out.print(calories+" ");
}
}
System.out.println("");
} catch(FileNotFoundException e){ // catches exception in case the file is missing
System.out.println(e);
}
}
示例输入文件:
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900