If I remove input.nextLine() from the catch block, an infinite loop starts. The coment says that input.nextLine() is discarding input. How exactly is it doing this?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
input.nextLine(); // discard input
}
} while (continueInput);
}
}
One more thing.. The code listed below, on the other hand, works perfectly without including any input.nextLine() statement. Why?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter four inputs::");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int[] x = {a,b,c,d};
for(int i = 0; i<x.length; i++)
System.out.println(x[i]);
}
}
Because input.nextInt(); will only consume an int, there is still pending characters in the buffer (that are not an int) in the catch block. If you don't read them with nextLine() then you enter an infinite loop as it checks for an int, doesn't find one, throws an Exception and then checks for an int.
You could do
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required) " +
input.nextLine() + " is not an int");
}
Related
So basically I've been trying to get this small simple code to work but I'm running into the problem of making a loop. What I want to happen is basically this: User enters an Integer, if its not an integer it will display an error and ask for an Integer until and Integer is given. I'm having a difficult time setting up a loop cause I don't quite know what to do. Im pretty new and dumb so this is probably really easy but I'm kind of an idiot and suck at this but I'm learning.
Here's what I have.
import java.util.Scanner;
public class Loop{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}
}
You can use while loop for that.
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
break;
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
You need to use a loop (for or while) to your code. You can do it like this.
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
// add same condition to break the loop
}
// close the scanner
scan.close()
}
}
So I'm trying to make a simple calculator.
How do I make when I enter the first number, it works but if I insert "abc" it will give me an error.
How I make it in order when you write "abc" to say " please enter a number "
import java.util.Scanner;
public class calculator
{
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if ( c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
}
}
You can verify the input until be a int using a scanner property Scanner.hasNextInt()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Example:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
while (!test .hasNextInt()) test .next(); // Scanner Validation
int x = test .nextInt();
}
JavaDoc of Scanner
The error you get is an exception. You can actually "catch" your exceptions, so that when they appear, your program doesn't break, and you can do what is in place for that error (output a "Please, insert only numeric values" feedback?)
You can find some info on try-catch blocks here try-catch blocks
Try this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
} catch(InputMismatchException e) {
System.out.println("Please enter correct values.");
}
}
Modifications:
The error you are getting is known as RunTime Error or Exceptions due to wrong input type. In order to handle RunTime Exceptions, You need to use try and catch block.
try and catch blocks are used to handle RunTime Exceptions. If any error or exception occurs within try block then It will be thrown to catch block to be handled instead of terminating your program.
Try this:
boolean success = false;
while (!success) {
try {
y = test.nextInt();
success = true;
} catch (InputMismatchException e) {
test.nextLine();
System.out.println("Please enter a number.");
}
}
If you're willing to accept doubles instead of ints, java doubles have a built in method isNaN(), where NaN stands for Not a Number.
if (Double.isNaN(doubleValue)) {
...
}
I am new in java. I have written a program in which the user chooses how many numbers he wants to add. If the user enters a string it will throw an exception and the programs tell the user to enter all details again.
My problem is i want the program to ask the user to re enter details from that number which he entered wrong.
Eg: the user chooses to add 4 numbers but he enters the third number as string, the program should ask the user to re-enter from the third number and not the entire details again.
My code is as follow:
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;
while(loop)
try
{
String yn;
do
{
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
System.out.println("Try Again\n");
}
}
}
You can resolve this, by placing the "retry" one level deeper in the code:
import java.io.*;
import java.util.*;
class Add {
public static void main(String args[]) throws Exception {
boolean loop=true;
Scanner s=new Scanner(System.in);
while(loop) {
try {
String yn;
do {
loop = true;
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;) {
try {
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}
catch(Exception e) {
System.out.println("Invalid input. Try Again.\n");
}
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
loop = yn.equals("y")||yn.equals("Y");
} while(loop);
}
catch(Exception e) {
System.out.println("Number of elements invalid. Try Again.\n");
}
}
}
}
As #Zhuinden indicates, one better uses Scanner.nextInt, since it is more generic...
Below code should help
int i =1;
while(i <=num){
System.out.println("Enter number["+i+"]: ");
try{
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}catch(NumberFormatException ex){
System.out.println("Please enter a valid interger");
}
}
Use additional method that reads single entry until it is valid number:
private static int readNumber(Scanner s) {
Integer value = null;
while (value == null) {
try {
value = Integer.parseInt(s.next());
} catch (NumberFormatException e) {
System.out.println("bad format, try again...");
}
}
return value;
}
Then you can use this method whenever you can read valid number:
System.out.println("Enter how many numbers to add: ");
int num = readNumber(s);
...
System.out.println("Enter number[" + i + "]: ");
a = readNumber(s);
....
Method getNumber(s) guarantee to return only when user give correct integer.
works according to what you want, but not ethical
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;int pos=0;int num=0,sum=0;
while(loop)
try
{
String yn;
do
{sum=0;num=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
num=Integer.parseInt(s.next());
int a;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;pos=i;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
Scanner s=new Scanner(System.in);
int a=0;
for(int i=pos+1;i<=num;i++)
{ System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;}
System.out.println("The Sum is:"+sum);
}
}
}
So this is my code for a crash proof scanner class:
import java.util.*;
public class BPScanner {
Scanner kb = new Scanner(System.in);
public int nextInt() {
while (true) {
try {
String input = kb.nextLine();
int i = Integer.parseInt(input);
return i;
}
catch (NumberFormatException e1) {}
catch (NoSuchElementException e2) {}
System.out.print("\nPlease input an integer: ");
kb.close();
kb = new Scanner(System.in);
}
}
}
I am calling this class from another class:
public void scnr() {
while (true){
System.out.print("Type a num (for test), (0 to break)");
int n = bpkb.nextInt();
if (n == 0) break;
System.out.println(n);
}
}
When I run it it returns an infinite loop that keep saying:
Please input an integer:
Please input an integer:
Please input an integer:
Please input an integer:
Any ideas how to fix it?
Thank you very much in advance.
Just remove the following codes from nextInt function:
kb.close();
kb = new Scanner(System.in);
If I enter the wrong input(example , if I enter String instead of Integer) loop is not ending, it wont get input next time. Here(below) i attach the entire program. can you please help this?. Thanks in advance!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* #author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
On an InputMismatchException you are doing i--, so the loop condition is modified to prevent the loop from ending without the needed input. If you read the API documentation for Scanner.nextInt() you should notice the following:
If the translation is successful, the scanner advances past the input that matched.
This means that if the input cannot be translated to int, the scanner does not advance. So on the next invocation of nextInt() it will re-read the exact same, non-int, input and fail again. You will need to read past that non-integer token before attempting to get an int again.
Again, don't mess with the loop index inside of the loop as this can cause problems down the road. Instead use a while loop which is much cleaner and much easier to debug 3 months from now:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
what about the below?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}