简体   繁体   中英

Using scanner to read integers from a file into an array

I'm working on a review assignment for school. The assignment is to write a class that reads from standard input a file containing several integers, which are to be put into an array. From here, methods need to be written that find the average, median, max, min, and standard deviation.

It reads like so:
45
56
67
78
89 etc...

So, I'm assuming I need to create an array list (since the length is undefined) and use scanner to read each line for an integer, then create the methods that will pick apart what I need. However, I fail to understand how to properly use FileReader and Scanner in conjunction. I'm currently running BlueJ. The text file is located under the project folder, yet the file is never found by the code.

Here is what I have so far.

import java.io.*;
import java.util.*;
import java.math.*;
public class DescriptiveStats
{
    public DescriptiveStats(){}
    public FileReader file = new FileReader("students.txt");

    public static void main(String[] args) throws IOException
    {
        try{
            List<Integer> scores = new ArrayList<Integer>();
            Scanner sc = new Scanner(file);
            while(sc.hasNext())
            {
                scores.add(sc.nextInt());
            }
            sc.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

确保“students.txt”与您运行的代码位于同一目录中(例如,将.java文件编译到的目录),或者将完整路径放到文件中。(“C:/ folder / students” 。文本”)

System.out.println(new File("students.txt").getAbsolutePath()); will give you the path from where java is trying to load the file.

I suspect its due to ambiguity caused by multiple paths in classpath, the first entry being the one from where it loads. Setting the file load path as the first entry should solve the problem.

Use Scanner.hasNextInt() (instead of Scanner.hasNext() ):

...
while(sc.hasNextInt())
{
    scores.add(sc.nextInt());
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM