I am Facing issues in Scanner Class in java - 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
}
}

Related

Loop when incorrect input is given?

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

how to use alternative of 'goto' in Java

How can I use any alternative to 'goto' in java?
I tried using break label. But since I am not breaking out of any loop, it is giving undefined label error.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
label1:
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{label2:
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label2
}
}
}
}
I was terminating the program on invalid input. But I need to execute the same lines on invalid input.
Rather than wanting to go to a specific point explicitly, wrap the bit you might want to repeat in a loop. If you don't want to execute the loop again, break.
For the first one:
while (true) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
// Nothing required to continue loop.
}
}
For the second one, wrap the loop body in loop:
for(int i=0; i<marksArray.length; i++)
{
while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
Or, probably better, write a method wrapping this loop:
int getInt(BufferedReader br) throws IOException {
while (true) {
try
{
return Integer.parseInt(br.readLine().trim());
} catch(NumberFormatException e) {
System.out.println("Please enter a whole number.");
}
}
}
and then call this method:
System.out.println("Enter no. of subjects");
int subNo = getInt(br);
for(int i=0; i<marksArray.length; i++) {
System.out.println("Enter marks for subject " + (i+1));
marksArray[i] = getInt(br);
}
This code snippet will loop until a correct number is inserted, in this example (it solves your first goto problem)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean noNumberEntered; //Default on false
System.out.println("Enter no. of subjects");
//TODO: check if input is integer
while(!noNumberEntered){
try
{
subNo = Integer.parseInt(br.readLine().trim());
noNumberEntered = true;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
I have reformatted your code a little bit. My basic idea was: All of the goto statements can be written in equivalent loops. The first one has now been made with a while loop, which terminates ones there comes NO exception. As for the second label, that has been done with the same mechanism (so a while-loop), however, with a label that can be exited/terminated with a "break + nameOfYourLable" - statement.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goToLabel1 = true;
while (goToLabel1) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
goToLabel1 = false; //parsing succeeded, no need to jump to label1
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{
label2: while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break label2;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
}
}
You can use a do while loop and a boolean instead, like that :
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goodEntry = true;
do {
goodEntry = true;
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
goodEntry = false;
}
} while(!goodEntry);
}
You can do the same with your second goto.
There are many ways to do that (with while loop and a boolean, with breaks...), but loops are better then goto.

How is nextLine() discarding input in this code?

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

How to resolve InputMismatchException?

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.

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.

Categories