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);
Related
I have written a JAVA program that takes input from the user and check if the user has entered the correct thing or not. I have taken the input from the Scanner class. If the user enters an invalid character like a String, I want to display 'Invalid Input'.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
int enteredNumber = takeInteger.nextInt();
}
}
Just ask the Scanner whether the next input is a valid int value, e.g.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
while(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
int enteredNumber = takeInteger.nextInt();
This will retry the operation until the user entered a number. If you just want a single attempt, use something like
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
if(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
else {
int enteredNumber = takeInteger.nextInt();
// ... proceed with the input
}
You will get an Exception that is InputMismatchException when an invalid input is passed.(i.e except integer value),you can use a try-catch block to hold the exception and inform the user about the invalid input. Try block , Catch block
import java.util.*;
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try{
int enteredNumber = takeInteger.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Enter a valid input");
}
You can use Exception handling for the same.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try {
int enteredNumber = takeInteger.nextInt();
}
catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
You can add a try-catch block in your program to check if the user's input is a number or not.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
String input = takeInteger.next();
int enteredNumber;
try
{
enteredNumber = Integer.parseInt(input); // Input is a number
}
catch(NumberFormatException ex)
{
System.out.println("Wrong Input!"); // Invalid input
}
You need to call the .nextLine method of the Scanner class and then parse to the desired type.
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
String line = sc.nextLine();
try {
int enteredNumber = Integer.parseInt(line);
System.out.println("You have entered: " + enteredNumber);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
Result with a number:
Enter a number
12
You have entered: 12
Result a text:
Enter a number
abcd
Invalid Input
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");
}
package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.
I a making a program that will ask an int input from user and check whether user input is an integer or not. If no the program asks for an input tile it gets a integer.
Scanner in = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
int num;
if (in.hasNextInt()){
num =in.nextInt();
if(num % 2 == 0){
System.out.print("this is even!!");
} else{
System.out.println("this is odd!!");
}
} else {
System.out.print("pleas enter an integer only!!!");
num = in.nextInt();
if(num % 2 == 0){
System.out.print("this is even second check!!");
} else{
System.out.println("this is odd second check!!");
}
}
here is the code but i have some mistakes in there. it brings an error when input is not an int. pleas help with this, thanks in advance!
Try the below code, it will end only if its a valid Integer otherwise it will keep asking for Integer and I think you are looking for the same.
public void checkInt() {
Scanner scanner = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
try {
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.print("this is even!!");
} else {
System.out.println("this is odd!!");
}
} catch (InputMismatchException e) {
System.out.println("pleas enter an integer only!!!");
checkInt();
}
}
You must read user input as String. Then, inside a try/catch block, make a casting to integer (Integer.parseInt()), if throws a exception is because is not a number.
May be a stupid way but this can solve your problem:
String x;
x = "5";//or get it from user
int y;
try{
y = Integer.parseInt(x);
System.out.println("INTEGER");
}catch(NumberFormatException ex){
System.out.println("NOT INTEGER");
}
Edited:
The program will try to convert the string to integer. If it is integer it will succeed else it will get exception and be caught.
Another way is to check the ASCII value.
To continue till integer is encountered:
String x;
Scanner sc = new Scanner(System.in);
boolean notOk;
do{
x = sc.next();
notOk = check(x);
}while(notOk);
System.out.println("Integer found");
}
private static boolean check(String x){
int y;
try{
y = Integer.parseInt(x);
return false;
}catch(NumberFormatException ex){
return true;
}
}
import java.util.Scanner;
public class Test {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
if(sc.hasNextInt())
System.out.println("Input is of int type");
else
System.out.println("This is something else");
}
}
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
}
}