java.lang.IllegalStateException: Scanner Closed error with java assignment - java

Exception in thread "main" java.lang.IllegalStateException: Scanner closed at 1070,1334. Java returned 1
This code reads from a Course.txt file located in the project folder, and after starting to read the text before finishing the first line it has this exception error. I am lost as this is the first time I have created a Java program for this.
I have double checked errors on netbeans with no help, also I tried removing and replacing certain areas of the code with no success.
package u2a1_readtextfilehandleexcep;
import java.util.Scanner;
import java.io.IOException;
//#author jeff thurston
public class U2A1_ReadTextFileHandleExcep {
public static void main(String[] args) throws Exception {
// TODO code application logic here
System.out.println("U2A1 Java Read Text File");
try
{
java.io.File file1 = new java.io.File("Course.txt");
Scanner input = new Scanner(file1);
while (input.hasNext())
{
String coursecode = input.next();
int coursehours = input.nextInt();
String coursetitle = input.next();
System.out.println ("Course code = " + coursecode + " -
Credit Hours = " + coursehours + " - " + "Course Title = " +
coursetitle);
input.close();
}
}
catch (IOException e)
{
System.out.println ("Error in reading the file" +
e.getMessage());
}
}
}
It should run as follows:
U2A1 Java Read Text File
Course code = IT2249 - Credit Hours = 6 - Course Title = Introduction to Programming with Java
Course code = IT2230 - Credit Hours = 3 - Course Title = Introduction to Database Systems
Course code = IT4789 - Credit Hours = 3 - Course Title = Mobile Cloud Computing Application Development
However after Course Title = Introduction in the first line is where the system stops producing output.

Related

Same Java code Failed to run under Java Gradle Application

I have come across an issue when running the following code under Netbeans Gradle Java Application.
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Main {
private static int imgBundle;
private static int flacBundle;
private static int vidBundle;
public static void main(String[] args) {
takeInput();
}
private static void takeInput() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of Image format for the order: ");
imgBundle = input.nextInt(); // where the error occurred
System.out.print("Please enter the number of Audio format for the order: ");
flacBundle = input.nextInt(); // where the error occurred
System.out.print("Please enter the number of Video format for the order: ");
vidBundle = input.nextInt(); // where the error occurred
System.out.println("Your Order Input:");
System.out.println(imgBundle + " IMG");
System.out.println(flacBundle + " FLAC");
System.out.println(vidBundle + " VID");
System.out.println("");
System.out.println("Calculating...Please wait...");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
An Error occurred
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at BundlesCalculator.Main.takeInput(Main.java:65)
at BundlesCalculator.Main.main(Main.java:43)
However, I wrote the same code in a simple Java Application without Gradle, there is no issue occurred.
I just wonder what did I do incorrectly?
Scanner will throw that exception if there is no more input to be read. This can happen if your input file is empty, or it doesn't contain enough data for all the nextInt() calls.
If input is from the terminal, you provided end-of-file (Ctrl-Z on Windows, Ctrl-D on Linux) before all the input was read.

Keep getting the java.util.NoSuchElementException on this program

I am currently writing a program that writes class codes to a file and then reads them back from said file and prints them to the screen. Everytime I run the program I keep getting the java.util.NoSuchElementException. This problem persists after every modification I have made and I'm not sure where to go from here. Any help would be greatly appreciated.
package u2a1_readtextfilehandleexcep;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class U2A1_ReadTextFileHandleExcep {
public static void main(String[] args) throws FileNotFoundException, IOException {
//Create new file called course.txt
java.io.File file = new java.io.File("course.txt");
if (file.exists()) {
System.out.println("File already exists; try another name.");
System.exit(0);
}
//Input the specified words to the file
try (PrintWriter output = new PrintWriter(file)) {
output.println("IT2249 6 Introduction to Programming with Java");
output.println("IT2230 3 Introduction to Database Systems");
output.println("IT4789 3 Mobile Cloud Computing Application Development");
}
try (
//Reads from file to the console
Scanner input = new Scanner(file)) {
while (file.canRead()) {
String code = input.next();
int creditHours = input.nextInt();
String courseTitle = input.nextLine();
System.out.println("Course Code = " + code + " | Credit Hours = " + creditHours + " | Course Title = " + courseTitle);
}
input.close();
}
}
}
And after running the program:
Course Code = IT2249 | Credit Hours = 6 | Course Title = Introduction to Programming with Java
Exception in thread "main" java.util.NoSuchElementException
Course Code = IT2230 | Credit Hours = 3 | Course Title = Introduction to Database Systems
Course Code = IT4789 | Credit Hours = 3 | Course Title = Mobile Cloud Computing Application Development
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at u2a1_readtextfilehandleexcep.U2A1_ReadTextFileHandleExcep.main(U2A1_ReadTextFileHandleExcep.java:26)
C:\Users\Deb\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
Once there are no more elements left to read, the Scanner will throw the exception you are seeing. Right now you continue to loop while you can read the file, but that has no bearing on where the Scanner is in the file. Scanner provides a family of functions to check the validity of the next tokens: hasNext(), hasNextInt(), hasNextLine(), etc. You should use these instead:
while( input.hasNext() ) {
String code = input.next();
// ...
}
However, if you have a malformed file, you could still get the exception for similar reasons reading the hours and titles. You can handle these by checking the scanner before reading them, or possibly in an exception handler since this probably indicates a larger problem, such as reading an unsupported or corrupt file.
Please call Scanner.hasNext(), so that the loop will terminate when
there are no more elements.
Don't close input explicitly as you are using the try-with-resources
which will take care of it.
There is no need of two separate try blocks, as they could be
combined together, once the writing is finished use the
PrintWriter.flush() to write it to disk.
package u2a1_readtextfilehandleexcep;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class U2A1_ReadTextFileHandleExcep {
public static void main(String[] args) throws FileNotFoundException, IOException {
//Create new file called course.txt
java.io.File file = new java.io.File("course.txt");
if (file.exists()) {
System.out.println("File already exists; try another name.");
System.exit(0);
}
//Input the specified words to the file
try (PrintWriter output = new PrintWriter(file);Scanner input = new Scanner(file)) {
output.println("IT2249 6 Introduction to Programming with Java");
output.println("IT2230 3 Introduction to Database Systems");
output.println("IT4789 3 Mobile Cloud Computing Application Development");
output.flush();
while (file.canRead() && input.hasNext()) {
String code = input.next();
int creditHours = input.nextInt();
String courseTitle = input.nextLine();
System.out.println("Course Code = " + code + " | Credit Hours = " + creditHours + " | Course Title = " + courseTitle);
}
}
}
}
file.canRead() will always return true and when read pointer reaches EOF, next input.read() operation fails.
Use input.hasNextLine() to check if EOF is reached.

Concatenate user input Strings to convert into a complete file path (Java)

I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:
import java.io.*;
import java.util.Scanner;
public class FilePractice {
public static void main(String[] args) {
//create a new File object
File myFile = new File("/home/christopher/Desktop/myFile");
try{
System.out.println("Would you like to create a new file? Y or N: ");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
myFile.createNewFile();
}
else
{
//do nothing
}
}catch(IOException e) {
System.out.println("Error while creating file " + e);
}
System.out.println("'myFile' " + myFile.getPath() + " created.");
}
}
I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.
Perhaps my syntax is wrong?
If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).
Here is the expanded attempt:
try {
System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
String fileName = input.nextLine();
input.nextLine();
System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
String userFilePath = input.nextLine();
File userFile = new File(userFilePath, fileName);
System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
String userChoice = input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
userFile.createNewFile();
//print for debug
System.out.println(userFile.getPath());
}
}catch(IOException e) {
System.out.println("Error while attempting to create file " + e);
}
System.out.println("File created successfully");
My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.
Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.
Changing input.nextLine() to input.next() solved the problem. The program was not reaching the if statement after asking the user if they were sure their entered path was the desired save point.
I also put in a simple else statement that printed out ("File not created") to verify that it was skipping it.
Anyway, question answered. :-)

Writing to a text file within a loop - JAVA

I've got a loop that reads through a text file and outputs it, now I'm trying to get it to loop through, and write what's printed out into a text file as I want it to display as HTML. This is what I've got so far for this method:
public void hChoice()
{
File fbScores = new File ("P:/SD/Assignment1/fbScores.txt");
String line = "";
try {
Scanner scanScores = new Scanner(fbScores);
while(scanScores.hasNext())
{
line = scanScores.nextLine();
stringArr = line.split(":");
if(stringArr.length == 4)
{
System.out.println("<h1>" + stringArr[0]+" [" +stringArr[2]+"] |" + stringArr[1]+" ["+ stringArr[3]+" ]<br></h1> ");
PrintWriter out = new PrintWriter("P:/SD/Assignment1/HTMLscores.txt");
out.close();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
I've added the HTML tags in the print out and it prints it out fine, but I've tried several different methods to get it to print to a text file but none have worked. Pretty new to Java so any help would be much appreciated. Thankyou. :)
You've gotten your syntax and code wrong for writing to files.
Please Google and check the right syntax for writing to files using java. Plenty of resources available. You'll learn better if you try it yourself.
FYR, here is one: http://www.tutorialspoint.com/java/java_files_io.htm

'error: cannot find symbol' Compiler Error

I've basically copied the below code from a text book. I've had this kind of error before and managed to fix it but because I'm not familiar with the Classes & Methods used I am having a bit a trouble with this one.
Below is the error thrown by the compiler.
TextReader.java:27: error: cannot find symbol output = new BufferedOutputStream(filePath.newOutputStream());
symbol: method newOutputStream()
location: variable filePath of type Path
Below is the code. It is basically supposed to get input from a user write it to a text file then read the text file and display the info to the user.
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
import java.io.*;
import javax.swing.JOptionPane;
public class TextReader
{
public static void main (String[]args)
{
Path filePath = Paths.get("Message.txt");
String s = JOptionPane.showInputDialog(null,"Enter text to save as a file","Text File Creator",JOptionPane.INFORMATION_MESSAGE);
byte[] data = s.getBytes();
OutputStream output = null;
InputStream input = null;
try
{
output = new BufferedOutputStream(filePath.newOutputStream());
output.write(data);
output.flush();
output.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Message: " + e,"Error!!",JOptionPane.WARNING_MESSAGE);
}
try
{
input = filePath.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String ss = null;
ss = reader.readLine();
JOptionPane.showMessageDialog(null,"Below is the information from the saved file:\n" + ss,"Reader Output",JOptionPane.INFORMATION_MESSAGE);
input.close();
}
catch (IOException ee)
{
JOptionPane.showMessageDialog(null,"Message: " + ee,"Error!!",JOptionPane.WARNING_MESSAGE);
}
}
}
Path doesn't have a method newOutputStream(). I usually use new FileOutputStream(File) for writing to files, though there might be newer API in Java 7.
You should really use an IDE, e.g. Ecplise or Netbeans, as it will instantly tell you that the method doesn't exist, and will make writing code a thousand times easier in general. For example you can press ctrl+space in Eclipse and it will bring up a list of classes/methods/variables that match the last word you typed (the list will also automatically pop up when typing a period).

Categories