I need help with an assignment I have to do for my class. I have only just started with Java so i'm pretty new with it. I need to write a code that will scan numbers from a text file then calculate them and create some averages. I used a for loop to scan the file but I don't know how to scan it so it skips every third line. I need each column of text rather than each line. The text file contains 3 columns and 7 rows.
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);
}
}
Example input file:
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900