0

I am using Java eclipse and I would like to have the user input the filename to retrieve a list of scores from the file. My goal is to take the average of those numbers. What line of code do I need just to get the user to input a file name and for the program to take those numbers so that I can compute with them? Currently I can have the user input scores, But I need to get the numbers from the file instead. I have visited numerous resources on this site. Here are a few:

BufferedReader, Error finding file, Getting a list from a file

package Average;
/**An average of scores*/
import java.util.Scanner;

public class Average2 {

    public static void main(String[] args) {
        int grade = 0;
        int students = 0;
        float total = 0;
        double average = 0;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter number of students: ");
        students = input.nextInt();

        if (students <= 10) {
            System.out.println("Enter the grades of the students: ");

            for(int i = 0; i < students; i++) {
                do {
                    grade = input.nextInt();

                } while(grade < 0 || grade > 100);

                total += grade;
            }

            average = (total/students);
            int median = ((82+84)/2);

            System.out.println("The average is " + average);
            System.out.println("The mean is " + median);


        }
    }
}

Update since above post!

package trials;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class trials2 {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    // Create new Scanner object to read from the keyboard
    Scanner in = new Scanner(System.in);

    // Grab the name of the file
    System.out.println("Enter filename: ");
    String fileName = in.next();

    // Access the file
    Scanner fileToRead = new Scanner(new File(fileName));

    // While there is still stuff in the file...
    double sum = 0;
    while (fileToRead.hasNext()) { 
                if (fileToRead.hasNextDouble()) {
                    sum += fileToRead.nextDouble();
                } else {
                    fileToRead.next();
                }   
            }
   {
            fileToRead.close();
        }

        System.out.println(sum);
}
}

The results I get from this:

Enter filename:

esp.txt <--entered by me

501.0

Community
  • 1
  • 1
spoilmealwayz
  • 69
  • 1
  • 8
  • 1
    Where will they input? Into the console? – user184994 May 26 '14 at 14:13
  • 2
    this looks like homework.. – DCarochoC May 26 '14 at 14:14
  • I am totally new to Java. I am taking a course on it now online and have no background on it :-/ I have tried this code: Scanner in = new Scanner(System.in); System.out.println("What is the filename?"); String input = in.nextLine(); Which allows me to get the user input, but I don't know how to get it to read it from there. – spoilmealwayz May 26 '14 at 14:19
  • while (in.hasNext()) { System.out.println (in.next()); } – rayryeng May 26 '14 at 14:38
  • You need to set up another counter that counts how many times you have read in a number. When you're done, divide your sum by this number. After `double sum = 0;`, place `int numStudents = 0;` Within the `if (filetoRead...)` statement, place `numStudents++;`. Finally, your last `System.out.println()` statement, do this: `System.out.println(sum/numStudents);` – rayryeng May 26 '14 at 18:31
  • That worked perfectly. Thank you @rayryeng ! I am forever grateful! – spoilmealwayz May 26 '14 at 20:30
  • You're very welcome. Good luck with everything, and thanks for accepting my answer! – rayryeng May 26 '14 at 20:44

3 Answers3

0
Scanner userInput = new Scanner(System.in);
System.out.println("ENter filename");
String fileName = userInput.next();
Scanner fileScan = new Scanner(new File(fileName));

then use scanner methods to process lines or string tokens you are interested in.

newbieee
  • 440
  • 1
  • 5
  • 17
  • Thank you @newbieee. I tried the code above to see if I can clear out some of the unnecessary text that came through after I got the file to import the numbers, but it underlines "new Scanner(new File(fileName));" in red and tells me I need to add throws declaration or surround with try/catch. I am so confused. I asked my professor if I should drop the class and take the intro, but he assured me I would be fine...now it is too late to drop and I need to learn all of this ASAP :( – spoilmealwayz May 26 '14 at 16:33
0

Look at the Java tutorial on Scanning: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html, particularly the ScanSum example. It shows how to scan double values from a text file and add them. You should be able to modify this example for your project.

Edwin Torres
  • 2,774
  • 1
  • 13
  • 15
0

Given that you want to find the average of numbers in a file, you could do something like this:

// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);

// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();

// Access the file
Scanner fileToRead = new Scanner(new File(fileName));

// Initialize our relevant counters
double sum = 0.0;
int numStudents = 0;

// While there is still stuff in the file...
while (fileToRead.hasNext()) { 
    // Is this next line consisting of just a number?
    if (fileToRead.hasNextDouble()) {
        // If it is, accumulate
        sum += fileToRead.nextDouble();
        numStudents++;
     } 
     else { // Else, just skip to the next line
         fileToRead.next();
     }   
}  
// Close the file when finished
fileToRead.close();

// Print the average:
System.out.println("The average mark is: " + (sum / numStudents));

This code will create a new Scanner object that will read input from your keyboard. Once it does that, you type in the file name, and it gets access to this file by opening another Scanner object. After that, we initialize some counters to help us calculate the average. These are sum, which will add up all of the marks we encounter and numStudents, which keeps track of how many students there are in the file.

The while loop will keep looping through each line of this file until it reaches the end. What is important is that you check to see whether or not the line you are reading in next consists of a single number (double). If it is, then add this to our sum. If it isn't, skip to the next line.

Once you're finished, close the file, then display the average by taking the sum and dividing by the total number of students we have encountered when reading the numbers in the file.

Just took a look at your profile and your profile message. You have a long road ahead of you. Good luck!

rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • Thank you for your help and understanding @rayryeng :) I tried the code above and it cannot locate the file in question. I tried using this solution (http://stackoverflow.com/questions/22973652/read-in-number-file-and-calculate-average-in-java) also and it got the file, however, it had a whole lot of text that wasn't in the file (text size info, style of text, etc) even though when I open the file it looks normal and only lists a few numbers. I have tried using the entire file path to locate file as well as just "esp.txt" – spoilmealwayz May 26 '14 at 16:26
  • The above code assumes that the file is located **in the same location** as where you are calling the program. That's probably why it didn't work, and I probably should have placed a small caveat in my post. Can you link me to where this file is? I'd like to take a look at it myself. My gut feeling is that you're reading in the wrong file. – rayryeng May 26 '14 at 16:29
  • I believe I have it in the same location as the program. I hope this is the info you needed from me.../Users/stephaniegross/Documents/workspace/Exam Statistics Program/src/Average – spoilmealwayz May 26 '14 at 16:45
  • Oh and I finally erased all of the formatting data that was appearing by downloading textwrangler (mac) and deleting what was not visible to me when using TextEdit. – spoilmealwayz May 26 '14 at 16:48
  • I wanted to see the contents of the actual text file itself. If this program is supposed to work, then there should **only be a number** for each line. – rayryeng May 26 '14 at 17:22
  • The content in the file is: 6 88 77 92 82 84 72 – spoilmealwayz May 26 '14 at 17:50
  • Are they separated by spaces or is there a new line after each number? – rayryeng May 26 '14 at 17:54
  • There is a new line after each number. I have made some progress since that last message, however. :D Thanks to the guidance I have received here from all of you. I will post what I have so far above for you all to see...so far I have the sum. Now I need the average but with omission of the first number (6) which is just the counter showing how many scores are to be added. I don't know how to do this yet, but I will be working on it :) – spoilmealwayz May 26 '14 at 18:18