Run Error in Java...Scanner closed? [duplicate] - java

This question already has an answer here:
java.lang.IllegalStateException: Scanner closed
(1 answer)
Closed 4 years ago.
So I have this code and it's supposed to read data from a file called "Numbers.txt". In this file, it is simply just 2003 lines of decimal numbers. The goal of the program is to read this file and make calculations. First I had to get the mean, which I've managed to do, but the problem is I have to now go back in and get the standard deviation. It compiles fine but I get a run error as below:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1115)
at java.util.Scanner.hasNext(Scanner.java:1379)
at StatsDemo.main(StatsDemo.java:49)
This is my code:
File rf2 = new File("Numbers.txt"); //reconnect to the FileReader object passing it the filename
Scanner inputFile2 = new Scanner(rf2);//reconnect to the BufferedReader object passing it the FileReader object.
sum = 0; //reinitialize the sum of the numbers
count = 0; //reinitialize the number of numbers added
//priming read to read the first line of the file
while (inputFile.hasNext()) //loop that continues until you are at the end of the file
{
difference = inputFile.nextDouble() - mean; //convert the line into a double value and subtract the mean
sum += Math.pow(difference,2); //add the square of the difference to the sum
count++; //increment the counter
if (inputFile.hasNextDouble())
inputFile.nextLine(); //read a new line from the file
}
inputFile.close(); //close the input file
stdDev = Math.sqrt(sum/count); //store the calculated standard deviation
I'm not sure why I'm getting this error. I got a similar (but not the same) one from the mean calculation earlier, but the resolve for that doesn't work for this. Any ideas?
After changing to inputFile2...
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1115)
at java.util.Scanner.next(Scanner.java:1510)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at StatsDemo.main(StatsDemo.java:51)

Replace inputFile with inputFile2 because it's the Scanner object.

Your Scanner is called inputFile2 not inputFile.

Rename inputFile to inputFile2 in code while (inputFile.hasNext())

Your Scanner object is with inputFile2 and you are using inputFile as a scanner object. I am surprised how is your code running without any compile errors. In case you have another file which is associated with inputFile Scanner object for which you have not provided code above, just check the file and closing of that reference where you are flushing the inputFile object. Otherwise, correct your code as below:
File rf2 = new File("Numbers.txt"); //reconnect to the FileReader object passing it the filename
Scanner inputFile2 = new Scanner(rf2);//reconnect to the BufferedReader object passing it the FileReader object.
sum = 0; //reinitialize the sum of the numbers
count = 0; //reinitialize the number of numbers added
//priming read to read the first line of the file
while (inputFile2.hasNext()) //loop that continues until you are at the end of the file
{
difference = inputFile2.nextDouble() - mean; //convert the line into a double value and subtract the mean
sum += Math.pow(difference,2); //add the square of the difference to the sum
count++; //increment the counter
if (inputFile2.hasNextDouble())
inputFile2.nextLine(); //read a new line from the file
}
inputFile2.close(); //close the input file
stdDev = Math.sqrt(sum/count); //store the calculated standard deviation

Related

Java hasNextLine() method

I am having a problem with the Scanner class method hasNextLine() (or the hasNext() method). Basically, I am trying to read from a text file that has a list of integer values. I need to read through the text file and store the values that are there in an array (not an arrayList). The code below first goes through the text file to "see" how many values are there. I'm doing this because I can't think of another way to count the total number of integers that are in the text file, and I need to know how long my array has to be.
That being said, once I do that it seems that the hasNextLine() method (or the hasNext() method) "stays" at the bottom of the text file once I loop through:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException
{
int y = 0; //stores numbers from the text file below
int counter = 0; //stores the number of datapoints in the text file to read from
File f = new File("Test Data.txt");// load an external file into a variable of type File.
Scanner reader = new Scanner(f);//instead of using System.in use f.
while (reader.hasNext()) // this will read the file's contents line-by-line
{
y = reader.nextInt();
counter++;/*stores the total number of integers in the Test Data.txt file so I can
know how long my array that stores the numbers from the txt file needs
to be.*/
}//ends loop
System.out.println("YOU HAVE " + counter + " DATA POINTS IN THE FILE");
int [] myNumbers = new int[counter]; //will store the integers from a data file
for (int i = 0; i < counter; i++){
if (reader.hasNext()){
System.out.println(i);
myNumbers[i] = reader.nextInt();
}//ends if statement
}//ends loop filling array
reader.close();
}
}
Is there a way to send the scanner "back to the top" of the text file WITHOUT creating a new scanner object? I know I could just create a new Scanner object, and then just loop and store each data point in an array, but it seems like there should be another way to do what I need to do. Is there? The documentation for the method in question doesn't mention much detail. I tried using the reset() method but that did not work.
I am not using an ArrayList because of a condition of the project I am working on. I understand that I could use an arrayList and not have to worry about counting the number of data values in the text file. However, the student I am helping has not learned about arrayLists yet as his class does not include them in the beginner course he's taking.
When reading the file for the second pass, just dispose the old scanner and get a new one. It is all in one line:
reader = new Scanner(f);
This will overwrite the reader with a reference to a new Scanner, one that reads from the beginning of the file. The old Scanner instance, which is no longer accessible will automatically be cleared by the garbage collector.

After reading data from file, why are local variables reassigned

Program asks for the name of a file. I have a file and trying to read data from it(contains only doubles) and then print the mean to an output file.
After looping through the file, I calculate and store the mean, which is stored in Results.txt. But, my local variables are underlined and my IDE says they are reassigned. Why? They are initialized and within the same method. Everything else in the code works, including the loop. I can't figure out why the mean isn't being sent to the file.
public class FileDemo {
public static void main(String[] args) throws IOException {
double sum = 0;
int count = 0;
double mean = 0; //The average of the numbers
double stdDev = 0; //The standard deviation
// Create an object of type Scanner
Scanner keyboard = new Scanner(System.in);
String filename;
// User input and read file name
System.out.println("This program calculates stats on a file.");
System.out.print("Enter the file name: ");
filename = keyboard.nextLine();
//Create a PrintWriter object passing it the filename Results.txt
//FileWriter f = new FileWriter("Results.txt");
PrintWriter outputFile = new PrintWriter("Results.txt");
//Print the mean and standard deviation to the output file using a three decimal format
outputFile.printf("Mean: %.3f\n", mean);
outputFile.printf("Standard Deviation: %.3f\n", stdDev);
//Close the output file
outputFile.close();
//read from input file
File file2 = new File(filename);
Scanner inputFile = new Scanner(file2);
// Loop until you are at the end of the file
while(inputFile.hasNext()){
double number = inputFile.nextDouble();
sum += number;
count++;
}
inputFile.close();
mean = sum / count;
}
}
sum, count, are flagged as reassigned variables.
mean is flagged as 'The value sum / count assigned to 'mean' is never used'
mean is flagged as 'The value sum / count assigned to 'mean' is never used'
This is exactly what it says. You do mean = sum / count; but you never use the value assigned to mean after this calculation. It looks like you have
outputFile.printf("Mean: %.3f\n", mean);
But remember that Java executes statements in order, so this will always print out 0.000. To fix this, you need to calculate the mean before writing it to the file.

Reading from a text file and changing the strings to int's to be entered in arrays is not working

Basically I am asking for the filename with a method called CS160Input (provided by my instructor) to ask for the filename. The text document has a bunch of entries each on their own lines, and I am trying to assign each number to a place in an array, but I am failing to actually write to the array. I know it is finding the file, because when i print out the counter, it tells me the correct amount of lines in the file. But when I try to print out a place in the array, I tried index 3 as you can see in my code, and it gives me 0 regardless of what I try. I tried creating an array of strings first and I ended up getting null for each index value as well.
public static void caclulate() throws FileNotFoundException {
String fileName = CS160Input.readString("Please enter the name of the file: ");
Scanner sc = new Scanner (new File (fileName));
int value, counter = 0;
int array[] = null;
while (sc.hasNextLine()) {
sc.nextLine();
counter++;
}
Scanner scanner = new Scanner(new File(fileName));
int[] calcArray = new int [counter];
int i = 0;
while(scanner.hasNextInt()){
calcArray[i++] = scanner.nextInt();
}
System.out.println(calcArray[3]);
System.out.println(counter);
}
Thanks to #Gendarme pointing out that hasNextInt() could be spitting out false if there were values in between, it made me take a closer look and I realized that in a previous program the numbers being written to the text file were doubles with 2 decimal places. Once I changed to hasNextDouble(), the program worked as intended.

Reading from third line of text file

How can I start reading from the third line of text file in Java?
I want to store 12 in 'nodes' variable, 14 in'edges' variable.
12334 in different variable and so on.
My input text file consisting of integers goes like this:
12
14
12334 12214 25
32151 32151 85
21514 51454 20
.
.
.
.
.
try
{
for(i=0;i<2;i++)
array[i] = inputFile.nextInt();
nodes=array[0];
edges=array[1];
break;
for(i=2;i<5;i++)
{
array1[i] = inputFile.nextInt();
System.out.println(array1[i]);
}
}
Using Scanner:
Scanner sc = new Scanner(myFile);
int lineIndex = 0;
while(sc.hasNextLine()) {
String line = sc.nextLine();
if(++lineIndex > 3) {
// do something
}
}
Note: Having break is going to terminate the outer loop
Suggestiones how to solve this
1 . Either use BufferReader or Scanner class.
2 . Have a counter variable set to zero
3. keep reading line and check if it is equal to 3 yet
4. continue reading line, but when the counter is equal 3, save each line in either variable or Array
Difference between BufferReader and Scanner
1. BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream.
2. Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String.
3. BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads.

Using FileReader, how can I read the next line of a list of #'s, and then multiply it by another value?

Say I have a file called AnnualRateOfReturn.txt with a list of numbers for each line. Lets call that variable X. The numbers read from the file will be percentages.
In a loop, I want to take one variable, lets say Y, and then multiply it by 1.X value read from the first line AnnualRateOfReturn.
After it loops again, I want it to take a new value, read from the next line of the file AnnualRateOfReturn.txt, and then multiply the Y value by the new 1.X variable.
For each loop, it should read the next line and then multiply the Y variable by that value.
Example:
AnnualRateOfReturn.txt
Line1: 0.04
Line2: 0.24
On the first loop, the Y value should be multiplied by 1.04
On the second loop, the next line should be read, and the Y value should be multiplied by 1.24
I need to accomplish this with the FileReader class.
//create a Scanner to scan through the file that FileReader reads
//note: must deal with FileNotFoundException
//which will be thrown if FileReader(source) cannot find the source file
Scanner scanner = new Scanner(new FileReader("path/to/AnnualRateOfReturn.txt"));
//scanner.hasNext() ensures that the scanner has a token to read
while(scanner.hasNext()){
//create your x value, this will throw an exception if the next token isn't a Double
double x = 1 + scanner.nextDouble();
//do your math
y = y*x;
}
use Scanner to read the file
Scanner sc = new Scanner("C:\\PATH_TO_THE_FILE\\AnnualRateOfReturn.txt");
now to read a line :
String line= sc.nextLine();
to get the value :
double x=1 + Double.valueOf(line);
if you want to test if file still has lines use :
while(sc.hasNext())
and then do the math ... good luck

Categories

Resources