`Enter Activity Number: Exception in thread "main" java.util.NoSuchElementException - java

Newbie here, The program works, I can call the class but I don't know what is this. I tried to search but it's not the same problem I encounter
import java.util.*;
public class mid_term {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean ok = true;
Act1 act_1 = new Act1();
do {
System.out.println("Midterm Project...Press [0] to exit.\n\n\n");
System.out.println("[1] Activity 1 (Grade Calculator).");
System.out.print("Enter Activity Number: ");
int choice = input.nextInt();
switch (choice) {
case 1:
act_1.main(args);
break;
default:
break;
}
} while (ok);
}
}
import java.util.*;
public class Act1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Prelim Grade: ");
double prelim = input.nextDouble();
System.out.print("Enter Midterm Grade: ");
double midterm = input.nextDouble();
System.out.print("Enter Final Grade: ");
double finals = input.nextDouble();
double result = ((prelim*.30) +(midterm*.30)+ (finals*.40));
System.out.println("Final Ratings: " + result);
input.close();
}
}
Enter Activity Number: Exception in thread "main" java.util.NoSuchElementException
How can I solve this?
Enter Activity Number: 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 mid_term.main(mid_term.java:23)

In the class Act1 you call
input.close();
it closes your System.in stream in the end of the 1st iteration.
In the class mid_term you have an infinite loop, if you want your program work without NoSuchElementException, you should keep your stream open. Delete the
input.close();

I have noticed a couple of problems with your code, first of all you should not make another "main" method in your Act1 class. The main method is the first method that is invoked when you run your code, usually you only want to make one of them. There is also no reason to make it static because you created an Act1 object. Static methods are used when you dont need an object to invoke them.
The reason for why it gives you an error is because you are making two different scanners scanning System.in at the same time, I think. To fix this simply pass your scanner from the "mid_term" class to the method in Act1 (which you have hopefully renamed at this point). Also make sure not to close it at the end because otherwise it will just crash once the while loop in mid_term repeats itself.
You also might want to consider renaming "mid_term", in java it is common practise to spell the first letter of your class capitally and use camel case instead of underscores

Related

Scanner variable cannot be resolved

In my program, the user will be asked to input 3 integers. The integers will then be read using the Scanner class and listed back to the user.
This is my code:
import java.util.Scanner;
public class Echoer
{
public static void main(String[] args)
{
/* The Data Below Will Read The Numbers Input Into The Prompt*/
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Three Integers: ");
int number;
number = input.nextInt();
Scan.close();
System.out.println("Thanks. The Numbers You Entered Are: " + number);
}
}
This is the error it returns:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Scan cannot be resolved
Why does it return this error? How can I fix this issue?
In your code, you never defined what Scan was. Use input.close() rather than Scan.close().
Scan cannot be resolved
means that you never defined Scan. This is because you said Scan.close(). You need to change it to input.close() because input is the name of the instance of the Scanner class.
As others pointed out, you have to close input instead of Scan as shown below.
import java.util.Scanner;
public class Echoer
{
public static void main(String[] args)
{
/* The Data Below Will Read The Numbers Input Into The Prompt*/
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Three Integers: ");
int number;
number = input.nextInt();
input.close();
System.out.println("Thanks. The Numbers You Entered Are: "+number);
}
}

How to make a ONE static scanner global variable without closing scan constantly and use it within methods and the main method?

I want to create a static scanner but i will like to put the try catch block around it so it can automatically close avoiding resources
leaks and or this exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at softwareEngineer.UserApp1.main(UserApp1.java:82)
Essentially I only want to create one static scanner declaration and use it throughout the main program and includes the static methods, at this point my code will require to create separate scanner for each method and you are force "scan.close()". the code below will recieve a exception handling error due to multiple scanner that was open and did not closein the program.
I updated the code now i get null pointer exception
import java.util.Scanner;
public class UserApp1 {
static User currentCustomer = null; //single object
static Scanner scan;
//-------------------------------------------------------
// Create a list, then repeatedly print the menu and do what the
// user asks until they quit
//-------------------------------------------------------
public static void main(String[] args) {
scan = new Scanner(System.in);)//scanner to avoid resource leak
printMenu(); //print menu system from another function
String choice = scan.nextLine(); //reads an input
final String EXIT_now = "0";
final String BACK = "back";
while (!(choice.equalsIgnoreCase(EXIT_now))){
switch(choice) {
case 1: break;
case 2:
currentCustomer = loginInput();<---- errors happens here
if(currentCustomer != null){
System.out.println("You have successfully login");
}
break;
default:
System.out.println("Sorry, invalid choice");
break;
} //ends switch
printMenu(); //print menu system from another function
choice = scan.nextLine(); //reads an input
}//ends while
System.out.println("\t\t GoodBye!\n Thank you for trying our program.");
System.exit(0);
}//ends main
//----------------------------
// Print the user's choices
//----------------------------
public static void printMenu() {
System.out.println("\t\t The User Login System ");
System.out.println("\t\t ======================");
System.out.println("The Menu Options:");
System.out.println("1: Register an Account");
System.out.println("2: Login to your Account");
System.out.println("3: Reset Password");
System.out.println("0: Quit/Exit ");
System.out.println("Please enter your selection > ");
} //ends printMenu
public static User loginInput(){
System.out.print( "\nFollow the Prompts to Log-In to your Account \n ");
System.out.print( "\nPlease enter your userid : \n ");
String userid = scan.nextLine();// <---- errors happens here
System.out.print( "\nPlease enter your password: \n ");
String pass = scan.nextLine();
currentCustomer = AccountList.loginUser(userid, pass);
if (currentCustomer != null)
{
return currentCustomer;
}
return null;
}//ends loginInput
}//ends class*
You're using a try-with-resources, which will automatically close it when you finish the try block. Try setting it to a variable like so:
public class MyClass {
private static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
}
}
Avoid making multiple scanners with the System.in input as well, as they will consume the stream and then you have an entirely different problem.
Avoid using a static global Scanner at all, by passing the Scanner instance you want to work with to the relevant methods. Consider this simplified example:
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in)) {
String choice = in.nextLine().trim();
if(choice.equals("1")) {
doOp1(in);
} else if(choice.equals("2")) {
doOp2(in);
} else {
System.err.println("Invalid choice. Goodbye.");
}
}
}
// Method takes an open, functioning Scanner as an argument, therefore
// it doesn't need to close it, or worry about where it came from, it
// simply uses it, does what it needs to do, and returns, trusting
// the caller to properly close the Scanner, since it opened it.
private void doOp1(Scanner in) {
System.out.print("What is your name? ");
String name = in.nextLine().trim();
System.out.print("What is your favorite color? ");
String color = in.nextLine().trim();
}
private void doOpt2(Scanner in) {
...
}
You want to compartmentalize your resources to ensure they are limited in scope and easy to close. Putting them in global state of any kind makes that very difficult. Instead, separate the opening and closing of the resource from the code using it. This sort of compartmentalization makes for much more maintainable, readable, and testable code.
For instance, by passing an already open Scanner to your core business logic functions, you can mock a real user's behavior and create a test to ensure your code remains stable, by constructing a Scanner that reads from a hard coded String, and passing that into your method, without needing to run the whole class and type in the behavior your testing manually again and again.

NoSuchElementException when trying to call kb.nextInt()

Quick question. Still fairly new to Java and my test class is giving me this error.
Please enter length of tail: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at LeftArrow.drawHere(LeftArrow.java:18)
at ArrowTest.main(ArrowTest.java:75)
Here is the code for the test class
public class ArrowTest
{
public static void main(String args[])
{
RightArrow right = new RightArrow();
LeftArrow left = new LeftArrow();
System.out.println("RightArrow Class: Calling drawHere()");
right.drawHere();
System.out.println("LeftArrow Class: Calling drawHere()");
left.drawHere(); //Error pointing to this line
// (at ArrowTest.main(ArrowTest.java:75))
}
}
And here is the code for the RightArrow and LeftArrow classes, just the relevant code. I commented the lines that the error was referring to.
public class RightArrow extends ShapeBase
{
public void drawHere()
{
int lengthTail, widthHead;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter length of tail: ");
lengthTail = kb.nextInt();
System.out.print("Please enter an odd numbered width of arrowhead: ");
widthHead = kb.nextInt();
}
public class LeftArrow extends ShapeBase
{
public void drawHere()
{
int lengthTail, widthHead;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter length of tail: ");
lengthTail = kb.nextInt(); //Error pointing to this line at LeftArrow.drawHere(LeftArrow.java:18)
System.out.print("Please enter an odd numbered width of arrowhead: ");
widthHead = kb.nextInt();
}
I commented out the right.drawHere() in the test class and it seemed to work okay. So I am fairly convinced it is because I am calling the same method from two classes derived from the same abstract class. Is there a way that I can fix this? Thanks for your help!
EDIT: I found that if I don't close the kb from the first arrow class called upon it does not throw this error. I can only assume its because of me closing System.in which is why it's causing a problem. Can anyone explain to me why making another instance of Scanner(System.in) doesn't just re-"open" System.in?
Before calling the nextInt method, you can use the hasNextInt() method on the scanner object to check if there is a value to get, which can be used to avoid exception. Try this:
if (kb.hasNextInt()){
lengthTail = kb.nextInt();
}
In your case, I think you are not providing enough inputs, which could lead to NoSuchInputException.
Have a look at the Scanner class doc for more information.
The problem is with Scanner object where while you calling right.drawHere() there you initialized the Scanner kb with System.in this will buffer through all data available in System.in left it empty for future use therefore it is throwing NoSuchElementException in left.drawHere().
Solution:
Make Scanner object kb as static and accessible for both LeftArrow and RightArrow

Use of Scanner class in recursive functions

I am trying to use a recursive method/function, which uses the Scanner class. Closing the scanner, causes an exception to be thrown the next time the same method is called within the recursion. A workaround to this is not to close the scanner at all, but this is not a right approach. I suspect the same scanner object is used between recursive calls, so that's why closing it creates havoc. If my assumption is correct then closing the scanner in the last method call would be a valid workaround (i.e. no actual resource leak). Is there anything I may be missing before jumping into Scanner and related implementation code?
EDIT
The answers provided were really useful and enlightening. In summary, the problem is the constant re-opening and closing of the scanner, and not recursion per se. The reason I would avoid passing the scanner object as parameter is that this example simulates a larger project, calling multiple recursive functions and I would have to pass the scanner object in all of them.
On the practical side, and from the answers provided, I think just closing the scanner in the last recursive call would work without having any resource leaks. Any related opinions would be welcome, esp. if you see something wrong with my approach.
Here is an example of my initial experiment:
package scanner;
import java.util.Scanner;
public class Main {
public static void acceptValidInput() {
System.out.print("Enter a number greater than 10: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
// Adding this will make an exception to be thrown:
sc.close();
if (i <= 10) {
acceptValidInput();
}
}
public static void main(String[] args) {
acceptValidInput();
System.out.println("Your input is valid");
}
}
Once you start to consume an input stream using a Scanner, you should not try to read from it in any other way anymore. In other words, after you have constructed a Scanner to read from System.in, you need to use it for all further reading from System.in. This is because Scanner buffers input, so you have no idea how much input it has already consumed but not emitted yet.
Therefore, I recommend that you construct one Scanner, then use it for all the reading:
public class Main {
public static void acceptValidInput(Scanner sc) {
System.out.print("Enter a number greater than 10: ");
int i = sc.nextInt();
if (i <= 10) {
acceptValidInput(sc);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
acceptValidInput(sc);
System.out.println("Your input is valid");
sc.close();
}
}
It works:
package scanner;
import java.util.Scanner;
public class Main {
public static void acceptValidInput(Scanner sc) {
int i = sc.nextInt();
if (i <= 10) {
System.out.print("Enter a number greater than 10: ");
acceptValidInput(sc);
}
}
public static void main(String[] args) {
System.out.print("Enter a number greater than 10: ");
Scanner sc = new Scanner(System.in);
acceptValidInput(sc);
sc.close();
System.out.println("Your input is valid");
}
}
The result is:
Enter a number greater than 10: 4
Enter a number greater than 10: 5
Enter a number greater than 10: 11
Your input is valid
Process finished with exit code 0
Closing the scanner closes also the underlying input stream. In this case it is the System.in stream - you shouldn't do this. Either do not close it or create a single scanner for all method calls.
public class abc{
public void acceptValidInput() {
System.out.print("Enter a number greater than 10: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
// Adding this will make an exception to be thrown:
if (i <= 10) {
acceptValidInput();
}
}
public static void main(String[] args) {
while(true){
abc a=new abc();
a.acceptValidInput();
System.out.println("Your input is valid");
}
}}
try this.

Confusin Error with Scanner

I keep getting this error and I do not know why :
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Daily.takingData(Daily.java:33)
at Daily.main(Daily.java:20)
this is my code:
import java.io.*;
import java.util.Scanner;
public class Daily
{
private static int size;
public static void main(String[] args) throws Exception {
System.out.println("Please enter amount of rows");
Scanner scan1 = new Scanner(System.in);
size = scan1.nextInt();
scan1.close();
System.out.println();
takingData(size);
}
public static void takingData(int rows) throws Exception {
System.out.println("Enter 1 To View Number of Markets");
System.out.println("Enter 2 To View Start and End Dates of Markets");
System.out.println("Enter 3 To View Start and End Dates of Contracts");
System.out.println("Enter 4 To View Averages of Markets");
System.out.println("Enter 0 To Quit Program");
int choice = 0;
Scanner scan2 = new Scanner(System.in);
choice = scan2.nextInt();
System.out.println("Got here");
scan2.close();
if (choice == 0)
System.exit(0);
}
}
My Out put is :
Enter 1 To View Number of Markets
Enter 2 To View Start and End Dates of Markets
Enter 3 To View Start and End Dates of Contracts
Enter 4 To View Averages of Markets
Enter 0 To Quit Program
(error here)
You are getting an error because you close your scanner right after you scan:
size = scan1.nextInt();
scan1.close();
and then try to scan again in takingData
remove the scan1.close(); that is outside of your takingData.
When you close a Scanner, the InputStream that it is scanning from is also closed, in this case your System.in is being closed.
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Taken from Scanner javadocs
The problem is that you're closing the first instance of Scanner here
scan1.close();
which is closing the associated InputStream (System.in) - this prevents the second Scanner instance of reading from the stream.
Don't close the scanner. Also you could create a single instance of Scanner for reading all values.
From a design point of view I would move from static methods to an OO approach with the single Scanner instance created in the constructor of Daily and all methods becoming instance methods. This will help with testability of the Object.
public class Daily {
private final Scanner scanner;
public Daily() {
scanner = new Scanner(System.in);
}
public int getRows() {
System.out.println("Please enter amount of rows");
return scanner.nextInt();
}
public static void main(String[] args) throws Exception {
Daily daily = new Daily();
int rows = daily.getRows();
int mainOption = daily.getMainOption(rows);
switch (mainOption) {
case 0: // TODO: refactor to use enums
System.exit(0);
}
}
public int getMainOption(int rows) {
System.out.println("Enter 1 To View Number of Markets");
System.out.println("Enter 2 To View Start and End Dates of Markets");
System.out.println("Enter 3 To View Start and End Dates of Contracts");
System.out.println("Enter 4 To View Averages of Markets");
System.out.println("Enter 0 To Quit Program");
return scanner.nextInt();
}
}
The answer to your question is here: https://stackoverflow.com/a/13042296/1688441 for question:
java.util.NoSuchElementException - Scanner reading user input
I am quoting:
When you call, sc.close() in first method, it not only closes your
scanner but closes your System.in input stream as well. This you can
verify by printing its status at very top of the second method as :
System.out.println(System.in.available());
So now when you re-instantiate, Scanner in second method, it doesn't find any open
System.in stream and hence the exception.
Get rid of the initial int choice, and try this:
int choice = scan2.nextInt();
Shouldn't really make a difference, but it could help.

Categories

Resources