Validating Scanner input in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I stop my program from crashing when a non numeric value is entered? I'm aware of kbd.hasNextLong, but I'm unsure how to implement it.

This is how you can validate it :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean end = false;
long value;
while (end == false) {
try {
value = input.nextLong();
end = true;
} catch (InputMismatchException e) {
System.out.println("Please input the right LONG value!");
input.nextLine();
}
}
}
Note that input.nextLine() in catch-statement. If you type in some non-int text, it jumps into catch (cause Integer couldnt be read in nextInt), it printline message and then it goes again. But the value typed does NOT dissapiered so it crashes again even if you dont do anything.
The input.nextLine() "flushes" what you put in.
Using hasNextLong is other way (however I would prefer throwing an exception, because it IS an exception) :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean end = false;
long value;
while (end == false) {
if (input.hasNextLong()) {
value = input.nextLong();
end = true;
} else {
System.out.println("input the LONG value!");
input.nextLine();
}
}
}

A simple solution is to use exceptions.
int value;
do {
System.out.print("Type a number: ");
try {
value = kbd.nextInt();
break;
}
catch(InputMismatchException e) {
System.out.println("Wrong kind of input!");
kbd.nextLine();
}
}
while(true);

Related

Program throwing exception despite generic Exception e catch [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
public class TryCatch {
public static void main(String[] args) {
int Score[] = {5,3,9}; //my array
Scanner sc = new Scanner(System.in);
boolean flag=true; //boolean for the while loop that will keep on asking for input till the input is correct
System.out.println("Enter index: ");
int ind = sc.nextInt(); //taking input
while(flag){
try {
System.out.println("Value at index is = " + Score[ind]);
flag= false; //if input is correct, the bool turns false and loop stops
} catch (Exception e) {
System.out.println("Enter a valid value!");
ind = sc.nextInt(); //should ask for input again if the input isn't right
}
}
}
}
So the problem I am having is that the catch block works for ArrayOutOfBound exception, but not when I enter some other character like a letter. What should I do?
UPDATE:
I fixed the bug by creating a new instance of the scanner class object in the catch block.
sc = new Scanner(System.in);
Thank you all for your answers.
You need to initialize the scanner class object again to close the previous scanner and dump all the input in it.
Add this line to the end of your catch block-
sc = new Scanner(System.in);
It is happening because you are asking for integer input within the catch, which isn't handled anywhere else, try this:
int ind; //taking input
while(flag){
try {
find = sc.nextInt();
System.out.println("Value at index is = " + Score[ind]);
flag= false; //if input is correct, the bool turns false and loop stops
} catch (Exception e) {
System.out.println("Enter a valid value!");
continue;
}
}
The problem is that the exception is thrown outside of the try block. You read from the keyboard either before the try-catch block or in the catch block.
If an exception is thrown within a catch block that exception will not be caught. Also you need to clear the input with nextLine or you will get an infinite loop, the correct code would be as follows:
System.out.println("Enter index: ");
while (flag) {
try {
int ind = sc.nextInt(); //taking input
System.out.println("Value at index is = " + Score[ind]);
flag = false; //if input is correct, the bool turns false and loop stops
} catch (Exception e) {
System.out.println("Enter a valid value!");
sc.nextLine();
continue;
}
}
I believe you need to separate the exceptions (when catching multiple types) with a pipe operator (SQLException | IOException e)
for example.

Getting an error on my do while loop in the doAgain method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Getting an error on my do while loop in my doAgain method. Not sure why. Trying to use another Boolean method to check for mistakes in the user input :
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
do {
int digits = getDigits();
System.out.println(createNumber(digits));
} while (doAgain() != false);
}
public static int getDigits() {
Scanner kb = new Scanner(System.in);
System.out.println("How many digits do you want the num to be?");
int digits = kb.nextInt();
return digits;
}
public static String createNumber(int digits) {
Random r = new Random();
StringBuilder sb = new StringBuilder(digits);
for (int i = 0; i < digits; i++)
sb.append((char) ('0' + r.nextInt(10)));
return sb.toString();
}
public static boolean doAgain() {
do {
Scanner kb = new Scanner(System.in);
String answer;
System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
answer = kb.nextLine();
if (answer.equals("yes"))
return true;
else
return false;
} while (incorrect(answer) != false);
}
public static boolean incorrect(String answer) {
if (!answer.equals("yes") || !answer.equals("no"))
return true;
else
return false;
}
}
You should declare String answer=""; inside doAgain function. Otherwise you will get cannot find symbol error in this line
while (incorrect(answer) != false);
Modify doAgain function to this
public static boolean doAgain() {
String answer="";
do {
Scanner kb = new Scanner(System.in);
// String answer; // remove this
System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
answer = kb.nextLine();
if (answer.equals("yes")) {
return true;
} else {
return false;
}
} while (incorrect(answer) != false);
}
Here a some mistakes you made:
!answer.equals("yes") || !answer.equals("no") always returns true.
answer in } while (incorrect(answer) != false); is out of scope. You need to declare String answer = ""; before the do-while loop.
The loop never repeats, because of you if else which always returns in the loop.
The fixed code can be:
public static boolean doAgain() {
Scanner kb = new Scanner(System.in);
String answer = "";
do {
System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
answer = kb.nextLine();
} while (incorrect(answer)); // Better not use double negative
if (answer.equals("yes"))
return true;
else
return false;
}
public static boolean incorrect(String answer) {
if (answer.equals("yes") || answer.equals("no"))
return false; // answer is correct
else
return true; // answer is incorrect
}

mismatch exception handling [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
boolean z = false;
do {
try {
a = sc.nextInt();
z = true;
}
catch(Exception e) {
}
}
while(!z);
Try this. If you try an integer the first time it executes properly. However if you enter the wrong type of text it turns into an infinite loop even if you enter an int next and skips assigning the boolean value to true. Why is this?
Your problem is from not handling the end of line token and so the scanner is left hanging. You want to do something like so:
import java.util.Scanner;
public class Foo2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 0;
boolean catcher = false;
do {
try {
System.out.print("Enter a number: ");
a = sc.nextInt();
catcher = true;
} catch (Exception e) {
} finally {
sc.nextLine();
}
}
// !!while(catcher == false);
while (!catcher);
System.out.println("a is: " + a);
}
}
Also, while (z == false) is bad form. You're much better off with while (!z). This prevents the while (z = false) error, and is a cleaner way of expressing this.
edit for Marcelo:
Marcelo, thanks for your input and advice! Are you saying that the conditional in the if block below will not change the value of the boolean, spam?
boolean spam = true;
if (spam = false) {
System.out.println("spam = false");
}
System.out.printf("spam = %b%n", spam);
Because if it does change it, the coder wouldn't expect this if they intended to write if (spam == false), then there could be subtle and dangerous side effects from this. Again, thanks for helping to clarify this for me!

About some simple exception handling in Java

There are several questions I would like to ask, please refer the comment part I have added in the code, Thanks.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
/* Task:
prompt user to read two integers and display the sum. prompt user to read the number again if the input is incorrect */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a;
int b;
while (accept_a == false) {
try {
System.out.print("Input A: ");
a = input.nextInt(); /* 1. Let's enter "abc" to trigger the exception handling part first*/
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine(); /* 2. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it? */
}
}
while (accept_b == false) {
try {
System.out.print("Input B: ");
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) { /*3. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception? */
System.out.println("Input is Wrong");
input.nextLine();
}
}
System.out.println("The sum is " + (a + b)); /* 4. Why a & b is not found?*/
}
}
I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it?
The use of input.nextLine(); after input.nextInt(); is to clear the remaining content from the input stream, as (at least) the new line character is still in the buffer, leaving the contents in the buffer will cause input.nextInt(); to continue throwing an Exception if it's no cleared first
Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception?
You could, but what happens if input b is wrong? Do you ask the user to re-enter input a? What happens if you have 100 inputs and they get the last one wrong?You'd actually be better off writing a method which did this for, that is, one which prompted the user for a value and returned that value
For example...
public int promptForIntValue(String prompt) {
int value = -1;
boolean accepted = false;
do {
try {
System.out.print(prompt);
value = input.nextInt();
accepted = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine();
}
} while (!accepted);
return value;
}
Why a & b is not found?
Because they've not been initialised and the compiler can not be sure that they have a valid value...
Try changing it something more like.
int a = 0;
int b = 0;
Yes, it's okay. And will consume the non-integer input.
Yes. If we extract it to a method.
Because the compiler believes they might not be initialized.
Let's simplify and extract a method,
private static int readInt(String name, Scanner input) {
while (true) {
try {
System.out.printf("Input %s: ", name);
return input.nextInt();
} catch (InputMismatchException ex) {
System.out.printf("Input %s is Wrong%n", input.nextLine());
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = readInt("A", input);
int b = readInt("B", input);
System.out.println("The sum is " + (a + b));
}
I have put comment to that question line.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a=0;
int b=0;
System.out.print("Input A: ");
while (accept_a == false) {
try {
a = input.nextInt(); // it looks for integer token otherwise exception
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next(); // Move to next other wise exception // you can use hasNextInt()
}
}
System.out.print("Input B: ");
while (accept_b == false) {
try {
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next();
}
}
System.out.println("The sum is " + (a + b)); // complier doesn't know wheather they have initialised or not because of try-catch blocks. so explicitly initialised them.
}
}
Check out this "nextLine() after nextInt()"
and initialize the variable a and b to zero
nextInt() method does not read the last newline character.

Output keeps on running [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the output keep on running? When I run this program, and I enter the in the output, it keeps running, and doesn't let me enter any more numbers. Why is this happening?
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionTest2
{
public static void main(String[] args)
{
Scanner st = new Scanner(System.in);
int ab, bd, cde;
ab = bd = cde = 0;
boolean infinite, in;
do
{
System.out.println("Enter the numbers to divide");
infinite = false;
in = true;
try
{
ab = st.nextInt();
bd = st.nextInt();
infinite = false;
in = true;
}
catch (InputMismatchException e)
{
System.out.println("Invalid input");
in = true;
}
finally
{
if (in)
{
try
{
System.out.println("I am in try block before exception");
cde = ab / bd;
System.out.println("I am in try block after exception");
}
catch (Exception e)
{
infinite = true;
}
finally
{
if (!infinite)
{
System.out.println("Answer is " + cde);
};
}
}
}
}
while (cde != 100);
st.close();
}
}
problem:
ab = st.nextInt();
When you input a String on it I wont get consumed by the nextInt and no one will thus giving you infinite loop
solution:
You need to consume those characters that you inputted in your catch block to avoid the infinite loop
sample:
catch (InputMismatchException e) {
System.out.println("Invalid input");
st.nextLine();
in=true;
}

Categories

Resources