I'm right now trying to learn input/outputs and I have a really hard time with it. Currently, I'm stuck on one specific exercisefrom my study book, where I should write a program that reads a file containing two columns of floating-point-numbers, prompt the user for the file name, and then print the average of each column.
Is doing it all in main the easiest way, or should I arrange it into methods? This is what I've come up with so far:
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the File Name: ");
String fileNameReading = in.next();
in.close();
try {
getAverage(fileNameReading);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void getAverage(String fileNameReading1) throws IOException {
double firstColumnSum = 0; //Skapar summa för den första kolumnen
double secondColumnSum = 0; //Skapar summa för den andra kolumen
int allRows = 0; //Skapar summa för antalet rader
while (in.hasNextLine()) {
String[] row = in.nextLine().split("\\s+"); //Skapar arrayen rows
firstColumnSum += Double.parseDouble(row[0]);
secondColumnSum += Double.parseDouble(row[1]);
allRows++;
}
double row1 = firstColumnSum / allRows;
double row2 = secondColumnSum / allRows;
in.close();
System.out.printf("Medelvärdet på den första kolumnen är: %.2f\n",row1);
System.out.printf("Medelvärdet på den andra kolumnen är: %.2f\n", row2);
}
The problem at the moment is that the scanner does not work since it's in another method than main, how do I get this to work?