Java Infinite Loop appears when using try/catch block - java

I am stuck in an infinite loop with this piece of code. The program generates endless lines of "Enter number 1> Please enter a number." when an invalid input like "a" is entered instead of an integer.
I don't know what's wrong with my boolean variable, everything seems fine to me. Please check it out, thank you so much.
import java.util.*;
public class Adder{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
boolean correctInput=false;
while(!correctInput){
try{
System.out.print("Enter number 1> ");
int num1=sc.nextInt();
System.out.print("Enter number 2> ");
int num2=sc.nextInt();
System.out.println("Sum = "+(num1+num2));
correctInput=true;
}
catch(InputMismatchException e){
System.out.println("Please enter a number.");
correctInput=false;
}
}
}
}

Add sc.nextLine(); statement in your catch block.

If you need to retry then add sc.nextLine(); otherwise you can break the loop as well by putting break; statement in catch block.

Related

Java: Program crashes after inputting two bad values

I coded a program, that calculates the gcd (greatest common divisor) and lcm (least common multiple). Everything works fine except the try {...} catch(...) {...}. Here is the part of the code that doesn't work as I want it to:
try {
num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
System.out.print("Enter your first number: ");
num1 = Integer.parseInt(sc.nextLine());
}
When I input e.g. letters, it says:
Your input is not an integer (number w/o decimals)! Try again.
Enter your first number:
But when I type letters the second time, the program crashes:
Exception in thread "main" java.lang.NumberFormatException: For input string: "asdf"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at GCDLCMgetter.main(GCDLCMgetter.java:56)
It is probably a very simple mistake I made but I can't figure it out...
Thank you
Your second parseInt method call is not in try catch block. You need to use a loop for this kind of logic.
It's because your second prompt is inside the catch block. Instead of prompting again inside the catch block, you want to wrap the entire code section in a loop so it comes back around to the try block for the prompt again.
Something like:
boolean repeat = true;
while(repeat){
try{
//Prompt for input
repeat = false;
}catch(Exception e) {
//Display error message
}
}
When the first time you give letters it goes into catch block. Displays the error message. And then executes the line num1 = Integer.parseInt(sc.nextLine());
Again you have entered the letters, but this time there is no try-catch block to handle this. So it throws error.
In your code, it gets executed twice:
Reads a Line at try{...}
There is an Exception
The Exception is handled by the catch(Exception e){...}
The num1 = Integer.parseInt(sc.nextLine()); inside the catch(Exception e){...} cannot be handled. It's not placed inside try{}.
Execution finished because the last exception cannot be handled by any catch.
It seems you're using Scanner, I would recommend you using a loop whis way:
while (sc.hasNextLine()){
try {
System.out.print("Enter your first number: ");
num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
}
}
If you're managing integers, it would be interesting using Scanner.nextInt()
while (sc.hasNextInt()){
try {
System.out.print("Enter your first number: ");
num1 = sc.nextInt());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
}
}

Why does this code keep looping and flooding the terminal when the input is not an integer?

Here's the code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Number: ");
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
} else {
System.out.println("Not an integer.");
}
}
scanner.close();
}
When the value is an integer everything works fine, the loop breaks out, however when the input is not an integer I keep seeing this infinitely flooding the terminal:
Number: Not an integer.
Number: Not an integer.
Number: Not an integer.
...
...
...
The reason this is happening when using Scanner.hasNextInt() in conjunction with Scanner.nextInt() is because the nextInt() method does not consume the ENTER key strike from the scanner buffer (when you enter a number) so this ENTER keeps getting played indefinitely. You need to clear this out of the Scanner buffer (so to speak) and to do that, you need to do this:
} else {
System.out.println("Not an integer.");
scanner.nextLine(); // Clear Scanner buffer.
}
Another reason why I just use Scanner.nextLine() ;).
OH...and don't close the Scanner object unless you are sure your application is finished with it otherwise you will not be able to use it again until you restart your application. It is auto-closed and Garbage Collected when the application closes anyways.
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
}
Because scanner.hasNextInt() is looking for an Integer input and if the input is integer it prints its value and breaks (break statement) the while loop (i.e come out of the loop) else it keeps scanning for integer input.
Also you are using condition true in while loop which means loop will keep executing infinitely until we break it.
That's simply because:
You are not taking out the non integer element (so it doesn't advance)
There is no other logic to leave the loop (while(true) is not nice anyway) if there is no integer.
You have entered an infinite loop if your scanner object does not recognize an integer input. Since you are not having a "break" inside the else{} block, it would loop through infinite number of times and flood the terminal. Insert a "break;" after the print statement
add break; after System.out inside else bracket , so you can break your loop once you encounter a non-integer input.
while(true)
{
if(Something) // What Ever
{
break;
}
}
System.out.println("Something Happened");
so if something happens you'll see Something Happened Once.
Edit:
If you want it to repeat asking, change it like this:
public static void main(String[] args) {
Scanner scanner;
while (true) {
scanner= new Scanner(System.in);
System.out.print("Number: ");
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
} else {
System.out.println("Not an integer.");
}
}
scanner.close();
}

Teach me why this code fails to check if my input is a int, and how I can fix it

import java.util.Scanner;
public class HelloWorld {
public static int num;
public static Scanner scan;
public static void main(String[] args) {
System.out.println("Hello World");
/* This reads the input provided by user
* using keyboard
*/
scan = new Scanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
check();
// Closing Scanner after the use
// Displaying the number
System.out.println("The number entered by user: "+num);
}
public static void check(){
try{
num = scan.nextInt();
}
catch (Exception e){
System.out.println("not a integer, try again");
check();
}
}
}
Im new to coding, and am taking this summer to teach myself some basics. I was wondering if someone could advise me on how I can create this method to take in a int, and check the input to make sure thats its a int. If the input is not a int, I would like to re run in.
Simple. Say you have something as shown below . . .
NumberThing.isNumber(myStringValue);
.isNumber() determines if your string is a numerical value (aka a number). As for putting the code in a loop to continue to ask the user for input if their input is invalid, using a while loop should work. Something like . . .
while (. . .) {
// use something to exit the loop
// depending on what the user does
}
You might consider moving the user request code to the check method. Also, use a break statement to exit your while loop after a valid number is entered.
while ( true )
{
System.out.println( "Enter an integer.");
try
{
num = scan.nextInt();
break;
}
catch (Exception e)
{
System.out.println("not a integer");
}
}

Java-Try and Catch Statement

I am just starting to write a blackjack game with java. I am trying to get the program to ask the user to enter again if the cash they typed in to start with isn't a valid integer. I see many examples of the try statement with catch, but none of them is working. The program gives the error InputMismatchException cannot be resolved to a type. A thread I have followed is this one, and I have the exact same code, just different variable name. Here it is.
Java InputMismatchException
Here is my code:
Scanner input_var=new Scanner(System.in);
System.out.println("Welcome to BlackJack!");
System.out.println("Enter how much money you will start with");
System.out.println("Starting cash must be whole number");
int money=0;
do{
try{
System.out.println("Enter how much money you will start with: ");
money=input_var.nextInt();
}
catch (InputMismatchException e){
System.out.println("Sry, not a valid integer");
input_var.nextInt();
}
input_var.nextLine();
}while (money<=0);
Any help with why my almost exact code isn't working would be greatly appreciated. Thanks for your time and effort.
Consume using input.next(), as input.nextInt() doesn't exist. That's the whole point of the Exception.
do{
try{
System.out.println("Enter how much money you will start with: ");
money=input_var.nextInt();
}catch (InputMismatchException e){
System.out.println("Sry, not a valid integer");
input_var.next();
}
}while (money<=0);
You can use hasNextInt() within a while loop. While the next input is not an integer, display the "not a valid integer" message and get the next input. When it is an integer, the while loop will break and you can do what you need to do.
Remove the input_var.nextInt(); from the try statement and input_var.nextLine();.
There has to be an import like this import java.util.* or import java..util.InputMismatchException.
Which IDE are you using?
Maybe you're looking for NumberFormatExcpetion? It's what gets thrown when converting strings to numbers. Try doing this instead:
Scanner input_var=new Scanner(System.in);
System.out.println("Welcome to BlackJack!");
System.out.println("Enter how much money you will start with");
System.out.println("Starting cash must be whole number");
int money=0;
do {
try {
System.out.println("Enter how much money you will start with: ");
money = Integer.parseInt(input_var.next());
}
catch(NumberFormatException e) {
System.out.println("Sry, not a valid integer");
input_var.next();
}
input_var.next();
} while (money<=0);

how to avoid pressing several time enter affects the input data?

I'm writting a JAVA Class to validate input data, especifically integer numbers.
The class I develop is running fine but when I press more than one time enter and then a char type, it display several times " Error!! Invalid number. Try again. " and I would like to avoid it.
I have use nextLine() method but it doesn't seems to correct it.
Here is the Class:
package chapter07.libro;
import java.util.Scanner;
public class Validator_integer
{
public static int getInt (Scanner scanner, String promt)
{
int numberInteger = 0;
boolean isValid = false;
System.out.println(promt);
while(isValid == false)
{
if(scanner.hasNextInt())
{
numberInteger= scanner.nextInt();
isValid = true;
}//if
else
{
System.out.println("Error!! Invalid number. Try again.");
}//else
scanner.nextLine();
}//while
return numberInteger;
}//getInt
}//Validator_integer
and next is the app to use the class:
package chapter.prueba;
import java.util.Scanner;
import chapter07.libro.Validator_integer;
public class Test_Validator_Integer
{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
int number = Validator_integer.getInt(sc, "Enter integer number: ");
System.out.println(number);
System.out.println("Continue (y/n): ");
choice = sc.next();
}//while
}//main
}//Test_Validator_Integer
The results I get are next:
Enter integer number:
2
2
Continue (y/n):
y
Enter integer number:
(Here I press several time enter)
xx
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
2
2
Continue (y/n):
n
So the part of (Error!! Invalid number. Try again.) displayed several times, is the one I would like to avoid.
Does any one know how to fix it???
Thanks in advance!!!
Before you read from System.in, make sure to "clear" it's contents to get rid of buffered/queued-up input. If there are n characters queued-up, then skip that many chars and you'll need to enter something new.
int n = System.in.available();
System.in.skip(n);
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

Categories

Resources