This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 19 days ago.
I'm new to Java, just started a couple days ago. I have this program wich does some cool checks on an input number, but for semplicity i just created a class TestToFixLoopIssue because loop is actually the issue im facing. When we choose to enter a number, we enter the if with choice == 1, so the Test class is called, does its things, and when we quit that "program" we get an infinite loop in the console. This does not happen if i just copy paste the Test code into the if (removing its Scanner). So i think its a problem related to the multiple Scanners, but i dont know how to fix it.
EDIT: i tryed adding s.next(); but this does not fix the issue, it just gives another error in console wich stops the program:
Exception in thread "main" java.util.NoSuchElementException
public class Program {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("What do you want to do?");
System.out.println("1. Check a number");
System.out.println("2. What is this program about?");
System.out.println("3. Quit");
if (s.hasNextInt()) {
int choice = s.nextInt();
s.nextLine();
if (choice == 1) {
System.out.println(" ");
// NumberChecker nc1 = new NumberChecker();
// nc1.check();
TestToFixLoopIssue test1 = new TestToFixLoopIssue();
test1.check();
} else if (choice == 2) {
System.out.println(" ");
System.out.println("This program checks multiple properties of a number.");
} else if (choice == 3) {
exit = true;
System.out.println(" ");
System.out.println("Program closed!");
} else {
System.out.println(" ");
System.out.println("Invalid choice. Try again.");
}
} else {
System.out.println("Invalid input. Try again.");
}
}
s.close();
}
}
public class TestToFixLoopIssue {
public void check() {
Scanner scan = new Scanner(System.in);
boolean repeat = true;
while (repeat) {
System.out.print("Insert a number: ");
int number = scan.nextInt();
System.out.println(" ");
System.out.println("You inserted " + number);
System.out.println("Do you want to check another number?");
System.out.println("1. Yes");
System.out.println("2. No");
if (scan.nextInt() == 2) {
repeat = false;
}
}
scan.close();
}
}
I dont want the loop to generate, so the user can keep using the program. I tryed some methods of the Scanner but neither of them worked, i dont actually know whats the issue exacty, so... help!
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
The expected output of the code is for a user to guess a randomly generated number between 0 to 100000, and for each guesses he pay $1.00, if the user guesses right he wins $1m, if not he is asked if he want a hint. each hint cost $2.00. so the code continues to run until the user quits the game or wins. the problem with my code is that after asking the user if he wants a hint or not the scanner input code doesn't run.
package com.company;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int guess, toguess;
String payOrQuit, yesOrNo;
double totalSpent = 0.0, hint, value;
boolean isWon = false, isQuit = false;
Random rand = new Random();
while (!isWon && !isQuit) {
toguess = rand.nextInt(1000000);
System.out.println("Want to win a million dollars?");
System.out.println("If so, guess the winning number (a number between 0 and 100000).");
System.out.print("Insert $1.00 and enter your number or 'q' to quit: ");
payOrQuit = input.nextLine();
if (payOrQuit.matches(".*\\d.*")) { // IF pays or quit
value = Double.parseDouble(payOrQuit);
System.out.println(toguess);
System.out.print("Guess a number: ");
guess = input.nextInt();
if (guess == toguess) { // IF 2 starts
System.out.println("YOU WIN!\nYou won $1000000!");
isWon = true;
} else {
totalSpent += value;
System.out.print("Sorry, good guess,Do you want me to give you a hint (y|n)?");
yesOrNo = input.nextLine();
if (yesOrNo.equals("y")) { // IF 3 starts
System.out.print("Insert $2.00 for the hint! : ");
hint = input.nextDouble();
totalSpent += hint;
if (guess > toguess) {
System.out.println("Guessed number too high");
} else {
System.out.println("Guessed number too low");
}
} else {
System.out.println("amount lost = " + totalSpent);
isQuit = true;
} // IF 3 ends
} // IF 2 ends
} else {
System.out.println("amount lost = " + totalSpent);
isQuit = true;
} // IF pays or quit ends//
}
}
}
The problem is because of input.nextInt() and input.nextDouble().
guess = input.nextInt();
Change it to
guess = Integer.parseInt(input.nextLine());
Similarly, also change
hint = input.nextDouble();
to
hint = Double.parseDouble(input.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.
I amm at my very beginning at java and just wanted to ask.
I want to ask the user to put Yes/No to a question and proceed to the next question. How do I do it?
import java.util.Scanner;
public class sff {
public static void main (String args[]) {
System.out.println("Hello There! We want to ask you some questions! but first: ");
System.out.print("Enter your age: ");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int age = num;
if( age == 12){
System.out.println("Hello Dan, I know you very well! ");
}
{
System.out.println("First question: ");
System.out.println("Do you exercise?(Yes/No) ");
// how do i proceed from here??
Use Scanner and get next line, then check if that line is yes or no then handle respectively.
In the example below, I used a while loop to keep asking them to input yes or no in case they enter something different like "maybe".
For example:
Scanner in = new Scanner(System.in);
// Loop until they enter either yes or no.
while(true){
String line = in.nextLine();
// Use this to check if it is yes or no
if(line.equalsIgnoreCase("yes")){
// Process yes
break;
}else if(line.equalsIgnoreCase("no")){
// Process no
break;
}else{
// Tell them to enter yes or no since they entered something else.
}
}
Are you looking for something like this?
//import to use the Scanner
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
//get the user input and store it as a String
String exerciseQuestion = in.nextLine();
//check what the user said.
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do you code when he exercises
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}
System.out.println("Ask your next question so on....");
}//main
}//class
If you want to deal with answers other than yes/no you can use this code:
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
String exerciseQuestion;
while (true){
//get the user input
exerciseQuestion = in.nextLine();
//check if user input is yes or no
if((exerciseQuestion.equalsIgnoreCase("yes")) ||
exerciseQuestion.equalsIgnoreCase("no"))
//if yes break and continue with your code
break;
else
//else loop back to get user input until answer is yes/no
System.out.println("Please answer with yes or no only");
}//while . i.e answer not yes or no
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do your code
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}//else
}//main
}//class
I have this try/catch wrapped around a do/while loop because after the try/catch throws the error message, I want it to loop back to the top. I tried do/while, while, and I tried placing the while loop at different places in my code but nothing works. The program works fine until an exception is thrown and then it goes into an infinite loop. After is displays the error message, I just want it to loop back up to the top.
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
break;
}
} while (true);
}
}
This is what it does after displaying an error message.
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
Enter a number?
If I don't stop it, it just keeps going.
you can try this workaround:
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
input.next();
}
} while (true);
}
}
or if you want to avoid try-catch:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Integer userInput = 0;
do {
System.out.print("Enter a number? \n");
if (input.hasNextInt())
userInput = input.nextInt();
else {
System.out.println(" That's not right ");
input.next();
}
if (userInput == 1)
Animal1.displayMessage ();//Display the total
;// Display the total
if (userInput == 2)
Animal2.displayMessage ();//Display the total
} while (true);
}
You can give 3 options - one option to exit
System.out.print("Enter a number? \n 1 to display Animal1 total\n2 to display Animal2 total\n 3 to exit");
Inside while loop, you can add
if ( userInput == 3) break;
You need to put the try/catch statements outside of the loop.
I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.
This question already has answers here:
How to repeat/loop/return to a class
(4 answers)
Closed 8 years ago.
I want to make a logic of getting grades. I proceed in a way of getting total marks as input from user using the Scanner class, then I'm validating marks if it is between 0 and 100(both inclusive).
Now if the marks are not in between this range, I print "Enter valid marks!!", and I want it to go to previous step and ask for the input from user again.
import java.util.Scanner;
class Performance
{
public static void main(String[] aa)
{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
}
// Now if this condition is true then I want the control to go again to line 7
// Please suggest me the way to Proceed
}
}
Please suggest the way to proceed with the modification in the above code.
See this link.
You want to do something like that:
do {
code line 1;
code line 2;
code line 3;
} while(yourCondition);
Now, if yourCondition is satisfied, the code will go to code line 1 again (will perform the code block between do and while).
Now, after you understand how it works, you can easily apply this to your task.
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
} else
break;
} while (true);
Try this:
boolean b = true;
while(b){
if(marks<0 || marks>100){
System.out.println("Enter valid marks!!");
marks= scnr.nextInt();
}
else{
b= false;
//Do something
}
}
8 int marks = scnr.nextInt();
9 while(marks<0 || marks>100)
10 {
11 System.out.println("Enter valid marks!!");
12 System.out.println("Enter the marks :");
13 marks = scnr.nextInt();
14 }
Thanks Guys for your help.
FInally i proceeded in the way as follows:
public static void main(String[] aaa)
{
int counter=0;
Scanner scnr = new Scanner(System.in);
int marks;
do
{
counter++;
System.out.println("Enter the marks :");
marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Marks entered are not valid");
if(counter>=3)
{
System.out.println("You have exceeded the maximum number of attempts!!");
System.exit(1);
}
else
System.out.println("Enter valid marks!!");
}
else
break;
} while(true);
}