Keep getting the java.util.NoSuchElementException on this program - java

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.

Related

Dose the if statement recognize the answer Scanner(System.in).nextLine() received?

If does not work when Y is entered as the statement.
+And how do I read and change config.cfg file?
My code is as below.
package myfirstpgram;
import java.io.*;
import java.util.*;
public class MidiBot {
public static void main(String args[]) throws InterruptedException, SecurityException, IOException {
File FolderDD = new File("./ProgramMF_Data"); // Set Program data to var(./ProgramMF_Data)
try {
FolderDD.mkdir(); // create Folder ProgramMF_Data
System.out.println("successfully created folder."); // print success to create folder
}
catch(Exception e) { //Catch error
e.getStackTrace(); // ?
e.printStackTrace(); // print error info 1
System.out.println("ERROR1 - Can't create Directory."); // print error info 2
System.exit(1);
}
System.out.println("Did you run the program for the first time? [Y/n]");
String FirstEM;
FirstEM = sc.nextLine();
if ("Y".equals(FirstEM)) {
System.out.println("Please Create ./ProgramMF_Data/config.cfg");
System.out.println("and set content like below");
System.out.println("\n[Config]"); //
System.out.println("FirstTime=1"); //
Thread.sleep(60000); // Sleep 60 seconds
System.out.println("\nProgram closes in 4 seconds!"); // info
Thread.sleep(4000); // sleep 4 seconds
System.exit(0); // Close program
}
System.out.println("Welcome again"); // print "Welcome again"
}
}
It looks like your post is mostly code; please add some more details.
your code seems correct, though an issue could arise when you enter a lower case "y".
a better approach would be
"y".equalsIgnoreCase(FirstEM);
And also you need to initialize scanner.
Scanner sc = new Scanner(System.in);
as for the config file, if it is a properties file then
check this link
You need to declare and initiaize a scanner before being able to use it
Please add Scanner sc = new Scanner(System.in); before using it.
I would also recommend you to take a small break and look up some naming conventions.

How to write a program that reads from and write to file

I'm reading a file with numbers checking if the number is a prime number then writing next to the prime numbers "is a prime" and printing that out to a different file,
I keep getting:
Failed to open file in4.txt Exiting...
This is my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class CheckPrimes {
public static void checkPrimes(String in_file, String out_file) {
File temp = new File(in_file);
Scanner input;
try
{
input = new Scanner(temp);
}
catch (Exception e)
{
System.out.printf("Failed to open file %s\n", in_file);
return;
}
while (true)
{
for (int i = 2; i < input.nextInt(); i++)
{
if (input.nextInt() % i != 0)
{
try{
PrintWriter output = new PrintWriter(out_file);
output.print( input.nextInt() + " is prime");
output.close();
}
catch(IOException ex)
{
System.out.printf("Error : %s\n",ex);
}
}
}
}
{
public static void main(String[] args)
{
checkPrimes("in4.txt", "out4.txt");
System.out.printf("Exiting...\n");
}
}
Longshot but might work since someone had that problem on this site yesterday. I referred them to this answer on a different topic where the File URL is formatted differently into a path that java seems to accept better that plaintext filepaths.
For the error you are receiving (Failed to open file in4.txt), just make sure that the file you are reading is on the same file level as your JAR (or file if running in an IDE). Alternatively, you can run the createNewFile() function and edit the created function.
(IntelliJ runs the file from the base of the project, hence why my files aren't where the class file is).
However, upon running the code myself, I was receiving this error: java.util.NoSuchElementException. I was able to correct this by switching from readInt() to readLine(), and having the in4.txt file structured as shown:
1
3
5
7
9
I believe readInt() not working versus readLine() is due to the problem presented in this problem. Also, be wary of calling readLine/readInt multiple times rather than assigning a variable per loop iteration because every call progresses the scanner (more info here).

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

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.

How Do I Compile/Run a java program from a Java Program (Input failure?)

Background info:
I am a high school student who is currently learning Java and as so if my code has an obvious flaw in it/ I accidentally reinvent the wheel with the code, I apologize.
Recently I have been working on writing an esoteric language and decided that I wanted to write it as an interpreter that translates the code to Java and then ran the code. My first step towards this was an attempt to create a mini-program that compiled and ran a java program. Most of the code from that was scrounged from another article, which is the third or fourth article I've looked threw:
how to compile & run java program in another java program?
I used the code from the third answer on that thread and initially thought that it worked. Unfortunately, when I tried running the code using the filename of the class for the program to be compiled and run within itself, the program failed.
Here is the modified code:
/**
*Functions printLines, Run, and parts of main came from stacks overflow
*originaly but modifications have been made
*https://stackoverflow.com/questions/4842684/how-to-compile-run-java-program-in-another-java-program
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
public class JTest
{
private static void printLines(String name, InputStream ins) throws Exception
{
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null)
{
//System.out.println(name + " " + line);
System.out.println(line);
}
}
private static int run(String command) throws Exception
{
System.out.println(command);//prints command
Process pro = Runtime.getRuntime().exec(command);
printLines(command, pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
// System.out.println(command + " exitValue() " + pro.exitValue());
return pro.exitValue();
}
public static void main(String args[])
{
System.out.println("Enter the name of the file you want to run: ");
Scanner cin = new Scanner(System.in);
String jFileName = cin.nextLine();
try
{
int k = run("javac " + jFileName + ".java");
if (k==0)
k=run("java " + jFileName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I also used another class:
public class Cout
{
public static void main(String args [])
{
System.out.println("Hello World");
}
}
In my initial test...
Output:
Enter the name of the file you want to run:
Input:
Cout
Output:
javac Cout.java
java Cout
Hello World
Here's what Happened when I tried to run JTest from JTest...
Output:
Enter the name of the file you want to run:
Input:
JTest
Output:
javac JTest.java
java JTest
Enter the name of the file you want to run:
Input:
Cout
After I entered this, nothing more was outputted onto the terminal window which leads to my main question:
Why didn't my code run the Cout class and how do I fix it? (Preferably in a way that makes my code compatible with both linux and windows) Or is there a resource someone could point me towards?
Your main issue is understanding input and output streams.
Every process has three standard streams: standard input, standard output and standard error.
When you normally run a program from a command shell, be it Windows CMD or Linux terminal/console, the standard input is attached to the terminal's input stream, and the standard output and error to the console output.
When you run a process from within Java, especially when you use Runtime.exec rather than use a ProcessBuilder, the standard streams are piped from and two the calling program.
What you type into your "front" program doesn't automatically go to the "back" program. The "back" program calls nextLine on a scanner on System.in. Its System.in is redirected to the "front" program through Process.getOutputStream(). It is waiting for something to come through from that pipe. But your "front" program doesn't write anything to that stream. The only streams it has taken care of are the standard output and standard error - the output from the "back" program which is input from the point of view of the "front" program.
So the "back" program will sit and wait and do nothing. And your "front" program at this stage is trying to read its output. It will not stop reading it until the "back" program terminates or closes its standard output. Which of course it doesn't do.
So the two processes are deadlocked. Each of them is waiting for something from the other process.
In fact, there is another possible problem with the way you handle your streams. For example, if the program has errors, those errors will be placed in the standard error stream. If the program terminates, good. But if not, you'll never get to reading the standard error, because you'll still be endlessly waiting for the "standard output" from that program, which may not exist at all.
A possible solution to all this is to have separate threads handling each of the streams.
One thread will need to read the console input ("front" program System.in), and pass anything it reads to the getOutputStream() (standard input of "back" program).
One thread will need to read the "back" program's standard output (getInputStream()), and send everything to its own System.out.
One thread will need to do the same for the error stream and System.err.
But the complication is that when the "back" program terminates, you need to have those threads stop, so that you can read your own System.in again and run another command. The output-handling threads are relatively easy - when the process terminates, they will see "end of file" and they can terminate then. But the "input" reading thread will need to have a mechanism that interrupts it when the "back" program terminated.
BTW, if you use ProcessBuilder to build your process, you'll have better control of the redirection of your input and output. You could let your program write its output and error messages directly to console. You'll still need to design the input properly - lines that are intended for the "front" program should not be consumed by mistake by the "back" program, so you can't do without redirection for input.
It works for me under Fedora 23.
Here is my output:
$ java JTest
Enter the name of the file you want to run:
Cout
javac Cout.java
java Cout
Hello World
I have both JTest.java and Cout.java in the current directory when I run them.
After looking at the answers above, I realized that I forgot that I could call the main method to create a bit of a workaround. So while I will need to create a variable string at some point, here is the code along with its input and Output.
Class JTest
/**
*Functions printLines, Run, and parts of main came from stacks overflow
*originaly but modifications have been made
*http://stackoverflow.com/questions/4842684/how-to-compile-run-java-program-in-another-java-program
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
public class JTest
{
private static void printLines(String name, InputStream ins) throws Exception
{
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
}
private static int run(String command) throws Exception
{
Process pro = Runtime.getRuntime().exec(command);
printLines(command, pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
return pro.exitValue();
}
public static void main(String args[])
{
System.out.println("Enter the name of the file you want to run: ");
Scanner cin = new Scanner(System.in);
String jFileName = cin.nextLine();
try
{
String arg[] = { "" } ;
int binary = cin.nextInt();
int k = run("javac " + jFileName + ".java");
if (k == 0)
if (binary == 1)
JTest.main(arg);
else
Foo.main(arg);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Class Foo
import java.util.Scanner;
public class Foo
{
public static void main(String args [])
{
Scanner cin = new Scanner(System.in);
int bar = cin.nextInt();
System.out.println("Your number times 2 is: " + (bar * 2));
}
}
Input Output Dialogue
Output:
Enter the name of the file you want to run:
Input:
JTest
1
Output:
Enter the name of the file you want to run:
Input:
JTest
1
Output:
Enter the name of the file you want to run:
Input
Foo
0
4
Output:
Your number times 2 is: 4
As the program demonstrates, both input and output work fine.

File writing in java [duplicate]

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
I've just started on my college journey ( 'Yay' ). I'm also new to the site so feel free to lecture me on things I may have done wrong as far as asking questions is concerned.
I was given a project, which has already been graded and all, and the program should ==>> first read lines of standard input (Input file name using keyboard) and for each line of input, if the user enters exit, the application terminates; otherwise, the application interprets the line as a name of a text file. The application creates or recreates this file and writes to it two lines of output, the name of the file and the current date and time. The application then closes the file, reopens it for reading, and writes its contents to standard output. The application writes to standard output the name of the file enclosed by square brackets. After writing the file name,
the application writes the contents of the file with each line prefixed by its corresponding line
number, a full colon, and a space.
I have worded it just as my professor did, so I apologize for any unclear statements. Here's what I got for it:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Project1
{
public static void main() throws IOException
{
String input = "";
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
try
{
File file = new File (input,".txt"); // Creates pointer to a file.
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
file.createNewFile();
file.getAbsolutePath();
printFileAndDate(file);
}
catch(IOException e)
{
System.out.print("Something wrong :(");
e.printStackTrace();
}
}
System.exit(0);
}
static void printFileAndDate(File temp)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("[ " + temp.getPath() + " ]");
System.out.println(dateFormat.format(cal.getTime()));
}
}
What I attempted to do there was the following:
-Get User Input => Save Input as a file => Call method "printFileAndDate" and print the file along with the current date and time in the correct format.
However, whenever I run it, it always gives me an exception error, which means the file was never really created or that it isn't able to find it.
The list of ISSUEs, I could find :
First, your main method signature is totally wrong
public static void main() throws IOException
change to
public static void main(String[] args) throws IOException
Second, it is not a good practice to throws exception inside main method.
The good practice is to use try catch block
Third, you have your Scanner varialbe after the while loop which does not make sense
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in); <-?!!!!!!
change to
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
while(!sc.equals("exit"))
{
Fourth , you define File variable this way
File file = new File (input,".txt"); <-- totally wrong
change to
File file = new File ("input.txt"); <-- if you use relative path
Fifth there is not need for System.exit(0);at the end of main method

Categories