The program I have below works perfectly when I print it out in the Java console but when I try to append the program to be put into a text file, it only prints 1/5 of the student's averages into the appending text file.
Bobby, average = 93
I want it to be printing all 5 student's averages as so
Agnes, average = 76
Bufford, average = 91
Julie, average = 94
Alice, average = 39
Bobby, average = 93
Thanks in advance.
import java.util.*;
import java.io.*;
public class StudentAverage {
public static void main(String[]args) throws IOException {
Scanner scanner = new Scanner(new
File("D:\\School\\StudentGrades.txt"));
while (scanner.hasNextLine()) {
Scanner scanners = new Scanner(scanner.nextLine());
String name = scanners.next();
double total = 0;
int num = 0;
while (scanners.hasNextInt()) {
total += scanners.nextInt();
num++;
}
PrintStream output = new PrintStream (("D:\\School\\WriteStudentAverages.txt"));
output.print(name + ", average = " + (Math.round(total/num)));
output.flush();
}
scanner.close();
}
}
PrintStream output = new PrintStream (("D:\\School\\WriteStudentAverages.txt"));
every time it gets to this line, it deletes the file ,opens a new file and adds only the current line. write this line before the loop, and in the loop just leave your other code as is.
To append your output/text file you have to use a different way of writing it.
I also suggest using try-with-resource blocks to avoid memeory leaks.
try (OutputStream output = new FileOutputStream("myFile.txt", true);
Writer writer = new OutputStreamWriter(output)) {
writer.write(name + ", average = " + (Math.round(total / num)) + '\n');
}
You don't have to flush/close them manually
There are a few more glitches in your code. Since you need to manage both the Scanner as well as the PrintWriter with a try/resource-construct, I'd prefer to keep the input- and output-routines separate and read the relevant contents of your file temporarily into memory.
Here is an idea:
LinkedHashMap<String, Integer> students = new LinkedHashMap<>();
// Input routine
try (Scanner scanner = new Scanner(new File("D:\\School\\StudentGrades.txt"))) {
while (scanner.hasNextLine()) {
try (Scanner scanners = new Scanner(scanner.nextLine())) {
String name = scanners.next();
int total = 0;
int num = 0;
while (scanners.hasNextInt()) {
total += scanners.nextInt();
num++;
}
students.put(name, (int) Math.round((double)total/num));
}
}
}
catch (FileNotFoundException e) {
// do something smart
}
// Output routine
try (PrintStream output = new PrintStream ("D:\\School\\WriteStudentAverages.txt")) {
for (Entry<String, Integer> student : students.entrySet()) {
output.println(student.getKey() + ", average = " + Integer.toString(student.getValue()));
}
}
catch (FileNotFoundException e) {
// do something smart
}
The above also allows you to get rid of that nasty throws IOException in the signature of your main()-method. Instead, there are now two beautiful skeletons of an exception handler (the two catch blocks) where you can put some logic that triggers in case
the input file has not been found / is not readable (first catch)
the output file isn't writable / cannot be created (second catch)
Related
I am new at Java so please bear with me.
I need help for one of my assignments again. Now it involves FileI/O.
The task that I have to do is:
I have to read a .csv file. The values that's inside the file are:
Christopher Lee,54.0
Stanley Wright,90.5
Oliver Stewart,75.8
Jessica Chang,34.65
As the task said, I must store the contents on the file into two arrays. One for the names, and one for the test marks. I should read the file at least twice, once to check how many names are in the file and a couple more times to actually read the file (to get the names and marks). So basically, I should have an array to store the names as Strings, and an array to store the marks of the student as real numbers.
I should line up the arrays (e.g.students[0] should store the name of the first student and marks[0] should store the mark of the first student
After I stored the contents of the .csv file into an array I have to display a following menu to the user. If the user pressed 1, it should prompt the user to enter the name of a student. If the user pressed 2, the program should exit. If the name exists, it should display the test mark for the student entered. If the student does not exist then I must output a message indicating so to the user, yet the program should not end but return to the above menu.
This is my code so far:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String fileName = "file:///Documents/Java/marks_file.csv"; // Opens the file
String[] arrayString = new String[6]; // String length inside the file
int numLines, selection = 0;
double[] arrayReal = new double[6]; // Number length inside the file
numLines = getNumLines(fileName); // Gets the length of the file
readFile(arrayString, arrayReal, fileName);
// Selection menu
do
{
System.out.println("Select an option:");
System.out.println("1. Display mark");
System.out.println("2. Exit");
selection = sc.nextInt();
if (selection == 1)
{
System.out.println("Enter your full name");
{
// Do something
}
}
else if (selection == 2)
{
System.out.println("Goodbye");
}
}
while (selection == 1);
//System.out.println("Number of arrays: " + numLines);
}
// Method to get the length of the .csv file
public static int getNumLines(String fileName)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
lineNum = lineNum + 1;
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
return lineNum;
}
// Method to store the values to arrays
public static void readFile(String[] arrayString, double[] arrayReal, String fileName)
{
Scanner sc = new Scanner(System.in);
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
for (int i = 0; i < arrayString.length; i++)
{
line = bufRdr.readLine();
arrayString[i] = processString(line);
arrayReal[i] = processReal(line);
}
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
// Stores the String lines to array
public static String processString(String line)
{
String string;
String[] lineArray = line.split(",");
return string = lineArray[0];
}
// Stores real number lines to array
public static double processReal(String line)
{
double real;
String[] lineArray = line.split(",");
return real = Double.parseDouble(lineArray[1]);
}
So far, I finished the "reading the file" part and processing the contents from a .csv file to an array.
I am not too sure how to prompt a user to search a string array from a .csv file. I tried looking at other sources, even at this website but I have no luck at all. I tried the Scanner.next() method but that doesn't work at all. Maybe I just missed something. Also, I am not sure if I did the "reading the file twice" right.
Am I on the right track? I am need of some guidance here
First of all I want to say that I'd use a Map instead of two arrays but I'll show you a solution using two arrays.
You were close to the solution. One of you problems is that scanner.next() only reads the input until the first whitespace. That's why you need to use scanner.nextLine(). This method reads the complete line. And the code could look something like that:
Solution with two arrays
Scanner sc = new Scanner(System.in);
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
for(int i = 0; i < arrayString.length; i++){
if(name.equals(arrayString[i])) {
System.out.println(arrayReal[i]);
}
}
Solution with a HashMap
Initialize HashMap
HashMap<String, Double> hm = new HashMap<String, Double>();
Fill HashMap
hm.put("Christopher Lee", 54.0);
Print double value of student
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
System.out.println(hm.get(name));
Instead of storing into arrays, I would rather tell you to pass the data to data into generic arraylist and then query the result using get() method.
You are making simple thing difficult.
Just use a HashMap with name as the keys and test-score as the values.
You open file
You read each line and translate each line to an entry of hash map
When a text is input to the console, you just get it from hash map, if existed return the value, if not then back to number 3
im trying to run a simulator and there are several problems, primarily....
-the code isn't printing out the values at the end of the program
- the code does not actually create the file
-I'm pretty tired so forgive any foolish mistakes I made or details I have left out.
I've searched the website and I found this
What is the simplest way to write a text file in java
and
how to write to text file outside of netbeans
I thought i could edit code from the first link to work for me, but that did not work( whcih is what you see here)
the second page looks more simple but there's no surrounding code so im not sure what the context is and how I would implement it
import java.util.Random;
import java.util.Scanner;
import java.io.*;
/*
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
*/
public class SimClass {
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in) ;
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0 ;
int pkt_dropped = 0;
int input ;
int output ;
int buffer ;
int x ;
double y ;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble();
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >=0 ; x--)
{ /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input/(output/buffer))
{
if (pkt_in_q < buffer)
{
pkt_in_q++ ;
}
else
{
pkt_dropped++ ;
}
//if statement should terminate here
}
else
if (pkt_in_q > 0)
{
pkt_in_q -- ;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content =( " pkt_in_q is " + pkt_in_q +
"pkt_dropped is " + pkt_dropped);
File file = new File("C:/Temp/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
try (BufferedWriter bw = new BufferedWriter(fw))
{
bw.write(content);
bw.close();
}
System.out.println("packets dropped value is = " +
pkt_dropped + "packets in q value is = " + pkt_in_q);
}
catch (IOException e)
{
//e.printStackTrace();
}
}
}
I think Code not executing due to file path error.
File file = new File("C:/Temp/inputFile.txt");
There is no folder called "Temp" in the C: drive. If u create Temp folder manually then the code will execute successfully.
File file = new File("D:/Temp/inputFile.txt");
I have created "Temp" folder in D: drive and code executed successfully.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0;
int pkt_dropped = 0;
int input;
int output;
int buffer;
int x;
double y;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble() * 10;
System.out.println("Y++++++" + y);
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >= 0; x--) { /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input / (output / buffer)) {
if (pkt_in_q < buffer) {
pkt_in_q++;
} else {
pkt_dropped++;
}
//if statement should terminate here
} else if (pkt_in_q > 0) {
pkt_in_q--;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content = (" pkt_in_q is " + pkt_in_q + "pkt_dropped is " + pkt_dropped);
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
// if file doesnt exists, then create it
if (!file.exists()) {
//file.mkdir();
file.createNewFile();
System.out.println("File created");
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("packets dropped value is = " + pkt_dropped
+ "packets in q value is = " + pkt_in_q);
} catch (IOException e) {
//e.printStackTrace();
}
}
Corrected the code check this and change the file directory and folder directory according to your requirement.
Correction for details:
First you can't define a try block like below
try (BufferedWriter bw = new BufferedWriter(fw))
It should be defined like
try{
}
catch(IOException e)
{
//do something
}
Modified code for that is like below:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try
{
bw.write(content);
bw.close();
}
catch (IOException e)
{
//e.printStackTrace();
}
Second you have to create the directory first post that you can create the file inside the directory. so just modified the code to get the directory created and file created.
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
Hope it clarifies your doubt.
I am making an app that keeps username and scores from a game in a txt file. The concept is that when it writes a new username and score to the txt file it should open the .txt file, read it and then make a clone of it adding a new uername and score entry in the txt file.
I am thinking of making this with 2 object arrays. The first is the one that is read in and the new will be the one is writen which will have one more entry.
So if player[i] is readen player[i+1] should be writen with new entry.
I am giving u the code below!
private Player[] myplayer=null;
private Player[] mynewplayer=null;
//open Players.txt
int i;
int n;
String filename="players.txt";
try
{
FileReader fp=new FileReader(filename);
BufferedReader bf=new BufferedReader(fp);
n=Integer.parseInt(bf.readLine());
myplayer=new Player[n];
int x=n+1;
mynewplayer=new Player[x];
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
bf.close();
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
n=myplayer.length;
try
{
filename="players.txt";
FileWriter fp=new FileWriter(filename);
fp.write(""+n+"\n");
for(i=0;i<n+1;i++)
fp.write(""+mynewplayer[i]+"\n");
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s="";
for(i=0;i<mynewplayer.length;i++)
s=s+mynewplayer[i]+"\n";
JOptionPane.showMessageDialog(null,"Players are \n "+s);
Problem is that when it's written, it returns null for mynewplayer.
I suppose the mynewplayer doesnt really take the entries of the "myplayer" but neither writes the new username.
Compile doesnt show any errors. Just writes NULL to the textfile.
Ask me if u want further info on the code writen!
Thanks in advance!
Here is an edited version of your code, with some improvements and there should be a comment around code that I changed, explaining what I did.
Player[] myPlayer = null; // first word uncapitalized, every
Player[] myNewPlayer = null; // other word begins with a capital
//open Players.txt
int i, n; // combine the variables into 1 line
String filename = "players.txt";
try {
FileReader fp = new FileReader(filename);
BufferedReader bf = new BufferedReader(fp);
n = Integer.parseInt(bf.readLine());
// not needed
//myPlayer = new Player[n];
// NOT NEEDED int x = n + 1;
myNewPlayer = new Player[n + 1];
for (i = 0; i < n; i++) {
String s = bf.readLine();
String user, score; // combine variables, doesnt need to initalize them
String[] items = s.split(","); // Splits the line into array elements on every delimiter -> ,
//user = s.substring(0, s.indexOf(","));
//s = s.substring(s.indexOf(",") + 1);
//score = s;
user = items[0];
score = items[1];
// this line below isnt actually needed
//myPlayer[i] = new Player(user, Double.parseDouble(score));
// Create a new player clone, dont copy the previous one
myNewPlayer[i] = new Player(user, Double.parseDouble(score));
}
// We've read all the variables from the text file, now we create the last one
// Since myNewPlayer is (n+1) size, the range of the array is
// 0 to n
// the last index will be n New Score Variable
myNewPlayer[n] = new Player("Username variable", Double.parseDouble("22"));
bf.close();
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
// This is called a ternary operator
// it is a 1 line if statement
// the format is like so
// booleanLogic ? trueAnswer Execution : falseAnswer Execution;
// if () { true }else { false }
n = myNewPlayer != null ? myNewPlayer.length : 0;
// CHANGED HERE - was using the first array rather than second
// dont need the 1st array
try {
filename = "players.txt";
FileWriter fp = new FileWriter(filename);
// Dont need "" before the items
fp.write(n + "\n");
for (i = 0; i < n; i++) {
fp.write(myNewPlayer[i] + "\n");
}
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s = "";
for (i = 0; i < myNewPlayer.length; i++) {
// s += ""; is like doing s = s + "";
s += myNewPlayer[i] + "\n";
}
JOptionPane.showMessageDialog(null, "Players are \n " + s);
I believe that your problem is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
You have nested loops, which is fine, but they use the same counter (the variable i ).
So what is happening is the first line of the file is read, and then added to myplayer[0]. However, instead of just also adding it to mynewplayer[0], you start another loop on i. This loop:
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
is going to copy the first player into mynewplayer[0]...and then null into every other entry (since myplayer only has the firsdt element filled.
The problem is that after that loop completes, i will equal n, so when you get back to the top of the outer loop, the check $i
Perhaps what you should do is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
mynewplayer[i]= new Player(user,Double.parseDouble(score));
}
mynewplayer[x]=new Player(<the new username>,Double.parseDouble(<the new score>));
I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.
Its easy when have a file of all doubles, but when
there is a non-double somewhere in between,
i wouldnt be able to catch all of them.
For example:
604.2
609.2
6042
604.4
4234.324
312
gfsdgfreg
6043
604.3
The output:
604.2
609.2
6042.0
604.4
4234.324
312.0
Apparently, two doubles are missing. Is there a way
to catch all of them just by using hasNextDouble()?
Thx in advance if u dont get a reply. I saw somewhere
that I could parse each of them to double and catch the
exception, but i am really not that advanced
what i have here is:
import java.util.*;
import java.io.*;
public class Lab11{
public static void main(String[] args)
throws FileNotFoundException{
File nums = new File("file.txt");
int size = arrSize(nums);
double[] phoneNums = copy(nums,size);
for(int i=0;i<phoneNums.length;i++)
System.out.println(phoneNums[i]);
}
public static int arrSize(File f)
throws FileNotFoundException{
int arrSize = 0;
Scanner in = new Scanner(f);
while(in.hasNextDouble()){
arrSize++;
in.next();
}
in.close();
return arrSize;
}
public static double[] copy(File f,int size)
throws FileNotFoundException{
Scanner in = new Scanner(f);
double[] list = new double[size];
int i = 0;
while(in.hasNextDouble()){
list[i++] = in.nextDouble();
}
in.close();
return list;
}
}
I would give your two while loops the following structure:
while(in.hasNext()) {
if(in.hasNextDouble()) {
// your inner while loop code here
} else {
in.next();
}
}
Otherwise, you'll miss everything after the first instance of a non-double.
Since you are using
while(in.hasNextDouble()){
arrSize++;
in.next();
}
As soon as it reaches a non-double, it will stop, and won't proceed further.
You have to keep looping through every line in the while loop, and within this loop, use an if statement to check whether what you're reading is a double or not.
Like Takendarkk said, once a non-double is found in the input in.hasNextDouble() will evaluate to false, ending your loop.
Here is an example of a (hopefully) more simplified way of doing what you are doing:
// create a new list for our doubles
List<Double> doubles = new LinkedList<>();
try {
// open our doubles file reader
BufferedReader reader = Files.newBufferedReader(Paths.get("doubles.txt"), Charset.defaultCharset());
// read our doubles file
String line;
while ((line = reader.readLine()) != null) {
if (line.matches("^[0-9]*(\\.[0-9]+)?$")) {
doubles.add(Double.parseDouble(line));
}
}
// close our doubles file reader
reader.close();
} catch (IOException e) {
e.printStackTrace(); // for the sake of the example
}
// output our doubles
for (Double d : doubles) {
System.out.println("Double: " + d);
}
Hope this helps