Java While Loop - java

Whenever I try to run this loop, I receive:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at test.readNumber(Lab2.java:28)
at test.go(Lab2.java:15)
at test.main(Lab2.java:7)
I'm trying to repeatedly prompt the user until the keyboard input is positive. Can anyone tell me how I can go about doing that without running into error?
public int readNumber() {
int x = keyboard.nextInt();
while (x < 0) {
System.out.println("Please enter a positive number.");
x = keyboard.nextInt();
}
return x;
}

It is always a good idea to check the docs. The exception is thrown if input data doesn't match the "Integer" pattern. Wrap input with try/catch:
public int readNumber() {
int x = -1;
while (x < 0) {
System.out.println("Please enter a positive number.");
try {
x = keyboard.nextInt();
} catch (java.util.InputMismatchException e) {
// oops, wrong input
}
}
return x;
}

public int readNumber() {
int x = -1;
do {
try {
System.out.println("Please enter a positive number.");
x = keyboard.nextInt();
} catch (InputMismatchException e) {
// normally you always want to handle the exception but in this case it is okay because mismatched input is the same as a non-positive integer input
}
} while (x < 0);
return x;
}

You are either not supplying an integer or giving a value for an integer which is out of range.

You have to read the EOL after reading te int value.
public int readNumber() {
int x = keyboard.nextInt();
keyboard.readNextLine();
while (x < 0) {
System.out.println("Please enter a positive number.");
x = keyboard.nextInt();
keyboard.readNextLine();
}
return x;
}

Related

Do while infinite loop

I am trying to write a method that asks a user for a positive integer. If a positive integer is not inputted, a message will be outputted saying "Please enter a positive value". This part is not the issue. The issue is that when I try to implement a try catch statement that catches InputMismatchExceptions (in case user inputs a character or string by accident), the loop runs infinitely and spits out the error message associated with the InputMistmatchException.
Here is my code:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
Essentially what is happening is that the scanner runs into an error when the given token isn't valid so it can't advance past that value. When the next iteration starts back up again, scanner.nextInt() tries again to scan the next input value which is still the invalid one, since it never got past there.
What you want to do is add the line
scanner.next();
in your catch clause to basically say skip over that token.
Side note: Your method in general is unnecessarily long. You can shorten it into this.
private static int nonNegativeInt() {
int value = 0;
while (true) {
try {
if ((value = scanner.nextInt()) >= 0)
return value;
System.out.println("Please enter a positive number");
} catch (InputMismatchException e) {
System.out.println("That is not a valid value");
scanner.next();
}
}
}
you are catching the exception but you are not changing the value of variable proper value so the catch statement runs forever. Adding properValue = true; or even a break statement inside the catch statement gives you the required functionality!
I hope I helped!
You can declare the scanner at the start of the do-while-loop, so nextInt() will not throw an exception over and over.
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
scanner = new Scanner(System.in);
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
This is indeed nearly identical to SO: Java Scanner exception handling
Two issues:
You need a scanner.next(); in your exception handler
... AND ...
You don't really need two loops. One loop will do just fine:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
continue;
} else if (variable >= 0) {
properValue = true;
}
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
scanner.next();
}
} while (properValue == false);
return variable;
}
Just add a break statement inside your catch.
Btw, you can get rid of the while loop by rewriting it like this:
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else {
properValue = true;
}
}
//...

How do I simplify this integer validation?

I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
You have:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.
A fix would be something like this:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
Try something more like (pseudo code):
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
With a little thought, you should be able use one "print error message" statement. But using two could be arguably better; it can tell the user what they did wrong.
What is the purpose of the String s parameter? Should you be checking that instead of a Scanner input?
Also, don't be surprised by mixing nextInt() and nextLine(). -- Source
I prefer using do-while loops for input before validation.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
I would say that this is a lot closer to what you're looking for, in simple terms...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
You should be able to abstract this code to suit your requirements.

Re-prompt after an exception in Java

I remember having this exact issue in Python. This Java code is a replica of my Python code which calculates the area of a triangle. I have it catch an exception if a non-number value is entered, but the end result gets botched.
private static float baseLength() {
float baseLength = 0;
Scanner user_input = new Scanner(System.in);
try {
while (baseLength <= 0) {
System.out.print("Enter the base length of the triangle: ");
baseLength = user_input.nextFloat();
if (baseLength <=0) {
System.out.println("Error. Plase enter a number higher than 0.");
}
}
} catch (InputMismatchException badChar) {
System.err.println("You have entered a bad value. Please try again");
baseLength();
}
return baseLength;
It will recover from bad numbers, but not from a value that is not a number. I still can't figure out what the exact issue is.
You can put the while loop around the try/catch block to achieve this:
private static float baseLength() {
float baseLength = 0;
Scanner user_input = new Scanner(System.in);
while (baseLength <= 0) {
try {
System.out.print("Enter the base length of the triangle: ");
baseLength = user_input.nextFloat();
if (baseLength <= 0) {
System.out.println("Error. Plase enter a number higher than 0.");
}
} catch (InputMismatchException badChar) {
System.err.println("You have entered a bad value. Please try again");
}
}
return baseLength;
}
with tests more clear, and exception inside principal loop, and every errors with System.err
private static float baseLength() {
float baseLength = 0;
while (true)
{
try {
System.out.print("Enter the base length of the triangle: ");
Scanner user_input = new Scanner(System.in);
baseLength = user_input.nextFloat();
if (baseLength>0)
return baseLength;
if (baseLength <=0)
System.err.println("Error. Plase enter a number higher than 0.");
}
catch (InputMismatchException badChar)
{
System.err.println("You have entered a bad value. Please try again");
}
}
}

For loop - validating input, program crashes (.hasNextInt())

I am writting a program in java that adds 5 numbers (positive integers) entered by the user using a for loop.
I have managed to make it work when the right input is given and even when negative integers are given, but the program crashes when a non int is entered.
Any help is appreciated!
for (int i = 0; i < 5 ; i++ ) {
if (myScanner.hasNextInt()) {
x = myScanner.nextInt();
if (x < 0) {
System.out.println("Invalid input, enter again:");
x = myScanner.nextInt();
}
}
else {
System.out.println("Invalid input, enter again:");
x = myScanner.nextInt();// this works in the nested if but not here, why?
}
sum += x;
}
System.out.println("Sum is: " + sum);
}//end class
You check whether the scanner has a next integer and then afterwards, still ask for an integer which it doesn't have...
Here's a corrected version:
for (int i = 0; i < 5 ; i++ ) {
if (myScanner.hasNextInt()) {
x = myScanner.nextInt();
if (x < 0) {
System.out.println("Invalid input, enter again:");
} else {
sum += x;
}
}
else {
// get whatever is on the scanner, since we know it isn't and int
String crud = s.next();
System.out.println("Invalid input "+crud+" enter again:");
}
}
InputMismatchException is being thrown, try this logic where the x = myScanner.nextInt is being called from one place,
int count = 0;
while (true)
{
try
{
if (myScanner.hasNextInt())
{
x = myScanner.nextInt();
if (x < 0)
{
System.out.println("Invalid input, enter again:");
}
}
else
{
System.out.println("Invalid input, enter again:");
continue;
}
}
catch(Exception e)
{
System.out.println("Invalid input, enter again:");
continue;
}
count++;
sum += x;
if(count==5)break;
}

Show error message instead of exception

I'm trying to make a program that gets a number from the user and checks the number is a prime number or not. I was thinking about the error handling. When the user enters a string the program should give an error message instead of an exception. I tried many methods but couldn't be successful. Could you guys help me with that?
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
if(inputNum < 0){
System.out.println("Please enter a possitive number.");
}
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
}
If user enters a non-integer input, this line
inputNum = input.nextInt();
will throw an exception (an InputMismatchException). The way Java handles exceptions is through a try-catch block:
try {
inputNum = input.nextInt();
// ... do domething with inputNum ...
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
Note: If you want to know more about exceptions (and you must) you can read Java tutorials.
just put it in try-catch and then print your message when exception occurs mean in the catch clause..its simple thing
If you need to check the input first and if it is a number check for prime and if it is invalid prompt user for another input until he enter a valid one, try this.
String inputString;
boolean isValid = false;
while(isValid == false){
//sysout for input
inputString = input.nextLine();
if(inputString.matches("[0-9]+")){
// check for prime
isValid = true;
}else{
//printin error
}
}
}
Thank you to every one especially to Christian. Here is the latest code.
import java.util.InputMismatchException;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
}
}

Categories