我需要帮助完成我必须为我的班级做的任务。我刚刚开始使用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
答案 0 :(得分:1)
这是一个非代码解决方案
有些java进入:
List<Integer> breakfast = new ArrayList<Integer>();
List<Integer> dinner = new ArrayList<Integer>();
List<Integer> lunch = new ArrayList<Integer>();
// add an element to breakfast:
breakfast.add(blammy);
// Iterate through dinner:
int dinnerTotal = 0
for (Integer current : dinner)
{
dinnerTotal += current.intValue();
}