Using a scanner to read integers from a file to an array

I am working on a solution for school. The purpose is to write a class that reads from standard input a file containing several integers that must be placed in an array. From here it is necessary to write methods that determine the mean, average, maximum, minimum and standard deviation.

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

So, I assume that I need to create a list of arrays (since the length is undefined) and use a scanner to read each line for an integer, and then create methods that will highlight what I need. However, I do not understand how to use FileReader and Scanner correctly. I am currently running BlueJ. The text file is in the project folder, but the file was never found by the code.

Here is what I still have.

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(); } } 
+4
source share
3 answers

Make sure that "students.txt" is in the same directory as the code you are using (for example, wherever your .java files are compiled) or put the full path to the .ie file ("C: / folder / students. txt ")

+2
source

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

I suspect this is due to the ambiguity caused by several paths to the class path, with the first entry being the one where it is loaded. Setting the file upload path as the first entry should solve the problem.

+1
source

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

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

All Articles