How to resolve InputMismatchException? - java

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.

Related

Input a number until -1

Create a program that asks the user to input numbers (integers). The program prints "Type numbers” until the user types the number -1. When the user types the number -1, the program prints "Thank you and see you later!" and ends.
This is the code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
System.out.println("Type numbers: ");
while(true)
{
number=Integer.parseInt(reader.nextLine());
if(number==(-1)) break;
}
}
When I check it, this is the error :
remember to read user input with Integer.parseInt( reader.nextLine() );
call it only once!
If I only call it once, how it will be possible to scan a lot numbers?
This is what you will use in this scenario. Using a do while loop, you can get your output
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int num = 0;
do {
System.out.println("Enter Numbers");
num = scan.nextInt();
} while (num != -1);
System.out.println("Thanks ! See you later");
}
Note: This runs until the user enters -1:
while (reader.hasNextLine()) {
number = Integer.parseInt(reader.nextLine());
if (number == -1) {
System.out.println("Thank you and see you later!");
break;
}
}
If you are always typing numbers I will use this:
final Scanner scanner = new Scanner(System.in);
boolean exit = false;
System.out.println("Type numbers:");
while (!exit){
if (scanner.nextInt() != -1)
exit = true;
}
System.out.println("Thank you and see you later!");
But you have to call scanner object each time you would like to read something from the imput.
You need to put System.out.println("Type numbers: "); inside while loop.
Since you are giving only integers as input, no need to parse it.
Below is required code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
// we need to loop "Type numbers:" each time umtil "-1" is pressed
while(number != -1)
{
System.out.println("Type numbers: ");
number=reader.nextInt();
}
// user must have been typed "-1" therefore it exits from whle loop
System.out.println("Thank you and see you later!");
// now there is nothing in main() fxn, therefore, the program will stop
}
}
Output:
Type numbers:
1
Type numbers:
3
Type numbers:
8
Type numbers:
9
Type numbers:
0
Type numbers:
-1
Thank you and see you later!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = -1;
do {
System.out.println("Welcome to Java Programming!");
System.out.println("Print Again? (y/n)");
num = input.nextLine();
} while (num.equalsIgnoreCase(-1));
}
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int flag=0,n;
while(flag!=1){
n=sc.nextInt();
if(n==-1){
flag=1;
}
}
System.out.print("Thank you and see you later!");
}
}

java Scanner force user to input a int value

public class Main{
public static void main(String args[]){
int i = nextInt();
}
public int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()){
scanner.nextLine();
Printer.println(Printer.PLEASE_NUMBER);
}
i=scanner.nextInt();
scanner.close();
return i;
}
}
The code above is how I'm trying to force a user to input a int value, but I get the nosuchelement exception, as the scanner.nextLine() reads a NULL.
In c++ the software waits for the user to input something. Is there anything I can do to force the program to stop, wait for the user to input something and then make the check?
EDIT:
So I'm having problems regardless, if I use scanner outside of Main class, it gives that error...
If you want the user to input and the scanner to pick up solely an integer value Scanner provides the method:
int i = scanner.nextInt();
Where i will store the next value entered into the console. It will throw an exception if i is not an integer.
Here is an example: Let's say I want the user to input a number and then I want to spit it back out to the user. Here would be my main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please print your number: ");
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
}
Now to check whether i is a integer you can use an if statement. However if you want the program to repeat until the user inputs an integer you can use a while loop or a do while loop where the loop's arguments would check if i is an integer.
Hope this is what you were looking for! By the way avoid naming your method nextInt() as the import java.util.Scanner; already has that method name. Don't forget imports as well!
You can do this:
public static void main(String[] args) {
System.out.println("" + nextInt());
}
public static int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!scanner.hasNextInt()){
System.out.println("Please enter a number:");
scanner.nextLine();
}
i = scanner.nextInt();
scanner.close();
return i;
}
This will cause the program to stop and wait for input each time the loop is executed. It will keep looping until it has an int in the scanner.
This works. There surely is a better solution.
EDIT As predicted. Check this,
import java.util.Scanner;
public class NewMain{
static boolean badNumber;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please print your number: ");
try{
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
badNumber = false;
}
catch(Exception e){
System.out.println("Bad number");
sc.next();
badNumber = true;
}
}while(badNumber);
}
}

Re-requesting input from user when an exception occurs

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);
}
}
}

Input compilation error Java

I need int num to only accept numbers. If I input letters I get an error. Is there a way to immediately flag letters, or do I have to take num in as a string and run loops?
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input a number.");
int num = input.nextInt();
}
}
You must use Scanner.hasNextInt():
It Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
public static void main(String[] args)
{
System.out.println("Input a number.");
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num = sc.nextInt();
System.out.println(num);
}
You probably want to do something like this:
import java.util.InputMismatchException
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input an integer.");
int num = 0; // or any other default value
try {
num = input.nextInt();
} catch (InputMismatchException e) {
System.out.println("You should've entered an integer like I told you. Fool.");
} finally {
input.close();
}
}
}
If the user enters something that is not an integer, the code within the catch block will be executed.

I am Facing issues in Scanner Class in java

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
}
}

Categories