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.
Related
I am working on a project that requires receiving and processing inputs from console. I use eclipse and accidentally discovered that when I press CTRL+Z in my console (without pressing ENTER after), the program crashes with a NoSuchElementException which I believe was thrown by the Scanner.nextLine() method. Below is the stripped down version of it.
Test.java
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
while(true) {
System.out.printf("Say something: ");
input = scanner.nextLine();
String output = input.trim().toUpperCase();
if(output.equals("Q")) {
break;
}
System.out.printf("Uppercase: %s\n", output);
}
scanner.close();
}
}
Here is my test run:
Say something: hey
Uppercase: HEY
Say something: i'm boutta crash this program by pressing ctrl+z
Uppercase: I'M BOUTTA CRASH THIS PROGRAM BY PRESSING CTRL+Z
Say something: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1656)
at Test.main(Test.java:11)
I also compiled the .java file with javac Test.java and run with java Test in Windows Command Prompt. Here is the output.
C:\>cd Test
C:\Test>javac Test.java
C:\Test>java Test
Say something: i'm gonna press ctrl+c
Uppercase: I'M GONNA PRESS CTRL+C
Say something: Exception in thread "main" java.util.NoSuchElementException: No line found
^C
C:\Test>
Are there any way to prevent CTRL+Z and CTRL+V from being read by the scanner? Thank you in advance for any help/explanations.
I tried surrounding the line input = scanner.nextLine(); with try/catch block. Here is my attempt.
try {
input = scanner.nextLine();
} catch(NoSuchElementException e) {
scanner = new Scanner(System.in);
System.out.printf("caught NoSuchElementException\n");
}
I got an infinite loop.
Say something: pressing ctrl+z...
Uppercase: PRESSING CTRL+Z...
Say something: caught NoSuchElementException
Uppercase: PRESSING CTRL+Z...
Say something: caught NoSuchElementException
Uppercase: PRESSING CTRL+Z...
Say something: caught NoSuchElementException
Uppercase: PRESSING CTRL+Z...
...
ctrl+z in windows or ctrl-d in Linux are DOS commands for the end of input. So, if you deploy your program in Linux, it will behave the same for the input of ctrl-d. You should handle this by calling method scanner.hasNextLine() which returns true only if there is input. I have attached the modified program, it runs. You may refer.
public class ControlPlusZ {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
while(true) {
System.out.printf("Say something: ");
if(scanner.hasNextLine()) {
System.out.println(scanner.hasNextLine());
input = scanner.nextLine();
String output = input.trim().toUpperCase();
if(output.equals("Q")) {
break;
}
System.out.printf("Uppercase: %s\n", output);
}
else {System.out.println("Closing scanner");
break;}}
scanner.close();
}
}
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.
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.
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner math = new Scanner(System.in);
System.out.println("What is 2 + 2?");
int num = math.nextInt();
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
}
catch(InterruptedException e)
{
System.out.println("Please, try again :-)");
}
int num1 = math.nextInt();
System.out.println(""); //Displays some message.
}
}
The code is supposed to display "What is 2 + 2?", a user inputs an answer, the code returns "Wrong." no matter what the answer. After a 2 second pause, the code displays "Please, try again :-)" and a user inputs an integer and the code returns a message.
The errors occur on the line with the catch token. The errors are:
Syntax error on token "catch", ( expected,
Syntax error, insert "-> LambdaBody" to complete LambdaExpression,
Syntax error, insert "AssignmentOperator Expression" to complete Assignment,
Syntax error, insert ";" to complete Statement
To use a catch in java you need to have a try. It is called a try..catch block. Please read the documentation here
So, adding a try as follows should get rid of the errors you are asking about here :
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
try // Looks like you missed the try here
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
} catch (InterruptedException e) {
System.out.println("Please, try again :-)");
}
I cant see try block. you can use this way also without try catch. Main method can throw InterruptedException ...
public class HelloWorld {
public static void main(String[] args) throws InterruptedException {
Scanner math = new Scanner(System.in);
System.out.println("What is 2 + 2?");
int num = math.nextInt();
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
}
int num1 = math.nextInt();
System.out.println(""); //Displays some message.
}
}
i tried to execute this code but it is not running and getting the following error
"Exception in thread "main" java.io.FileNotFoundException" and i don't know how to overcome..
class Showoccupancy{
public static void main(String args[]) throws FileNotFoundException
{
Scanner diskscanner = new Scanner(new File("Showoccupancy"));
System.out.println("Room \t guests");
for(int roomnum =0; roomnum<10; roomnum++)
{
System.out.print(roomnum);
System.out.print( " \t ");
System.out.print(diskscanner.nextInt());
}
}
}
can any one give solution for it?
This simply means that the file you are looking for does not exist in the directory of the java file that is executing the code. Also, make sure you include the relevant file extension in your name, i.e. Showoccupancy.txt