0

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?

Griezy
  • 45
  • 9
  • Get in the habit of writing one method for one task (and one task can be multiple steps, as long as the intermediary result is useless outside the task itself. Once you start needing it, split up the method). If speed is a project requirement, optimize once you find a bottleneck, and not before then. With that said: are you using an IDE? You have variables and methods that you don't actually call (in the code you're showing) so step one here would be to write a [mcve] so that people aren't going to point out you're doing things wrong when your "real code" is different from the code you show. – Mike 'Pomax' Kamermans Oct 18 '18 at 15:50
  • @Mike'Pomax'Kamermans Well, I tried writing one method for reading and one for printing, but It didn't work for me, so I just put it in main because I wanted to get the program to work and then split it up. As I said, the methods I'm not calling, are thet ones in the average method, which I coded just to show what I wanted to do. – Griezy Oct 18 '18 at 15:59

2 Answers2

0

This should work

package org.test; 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class readFile {

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 fileNameReading) throws IOException {
    FileInputStream fis;
    try {
        fis = new FileInputStream(fileNameReading);
         InputStreamReader input = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(input);
            String data;
            double avg = 0;
             String[] doublearray = null;


            while ((data = br.readLine()) != null) {
                doublearray = data.split(" "); // assuming the file contains only one line like x y , x and y are doubles
            }
            if(doublearray!= null && doublearray.length>0){
            avg = (Double.parseDouble(doublearray[0])+Double.parseDouble(doublearray[1]))/2;
            }

            System.out.println("The Average of Double values is : "+avg);


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
   }
}
iDevRoids
  • 33
  • 1
  • 5
  • I edited my original post to my current code, I'd appreciate if you could take a look at it. – Griezy Oct 18 '18 at 16:26
  • the scanner in your code is closed in main method only at line 4. To Read file contents with scanner , Check at this link : (https://stackoverflow.com/questions/13185727/reading-a-txt-file-using-scanner-class-in-java) – iDevRoids Oct 18 '18 at 16:30
0

Put these line in getAverage() just befor the while loop so that you start a new Scanner to read the contents of the file:

    File file = new File(fileNameReading1);

    Scanner in = null;

    try {
        in = new Scanner(file);
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
        return;
    }

Edit, this line:

in = new Scanner(file);


Constructs a new Scanner that produces values scanned from the specified file.


(from Scanner.java)
So the in Scanner object will be used to fetch the rows of your file.

forpas
  • 117,400
  • 9
  • 23
  • 54
  • this is exactly what I was looking for, thank you so much. I don't just want to paste it in without understanding the concept of this, so I'm going to try to look at each line and see what they do. I understand what every line does separately, but how exactly does the Scanner in the method read from the file the user typed in? The file in the method is just assigned to the argument string, which is what I don't really understand. – Griezy Oct 18 '18 at 18:26
  • Alright. One thing about the lines in the while loop though. I understand that a new String Array thats called row is created in the first line. What I do not fully understand is the split function and the parse command below. – Griezy Oct 18 '18 at 19:03
  • @Griezy Each line contains 2 numbers separated by a space. The `split()` method splits this line using the space as a separator (this is what `"\\s+"` stands for) in 2 strings and inserts them into the array `row`. Now `row[0]` and `row[1]` are the 2 strings but they must be converted to numbers in order to be used in calculations and this is done by the `Double.parseDouble()` method – forpas Oct 18 '18 at 19:09
  • Ah, now I see. Thank you so much for your help man. You've saved my day! – Griezy Oct 18 '18 at 19:48