so what I am trying to do is have the user input a valid coordinate in a matrix, that is an INT which is greater than -1,
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
the problem is that it loops endlessly after entering a not valid input
int R is the size of the row
int C is the size of the collumn
Your problem is that you're not handling the error you're catching.
If you'll provide wrong format of number for the nextInt() method, then the InputMismatchException will be thrown. Then because the catch does nothing, the loop will continue (start from begining) and the scanner will read the same incorrect value, and so on...
So instead of this:
catch (InputMismatchException e) {
}
Try this:
catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}
This way you'll force scanner to move past the last incorrect input.
EDIT:
You're loop is also broken because you do break after reading the input. In that case if you'll put the negative number you'll break as well and won't check the loop condition. Remove the break statement and it will work as expected:
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
EDIT2:
public static void main(final String args[])
{
int maxRowsNumber = 10;
int maxColsNumber = 10;
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
System.out.println("Inserted RowsNumber: " + coordinates[0]);
System.out.println("Inserted RowsNumber: " + coordinates[1]);
}
Output:
Please enter a valid row number: 11
Please enter a valid row number: 22
Please enter a valid row number: 10
Please enter a valid col number: 11
Please enter a valid col number: 2
Inserted RowsNumber: 10
Inserted RowsNumber: 2
If by "not valid input" you mean "not any kind of integer", then your scanner will fail each time it tries to read another integer, so you'll hit your catch, and do nothing to stop the loop. Maybe you intended to set check to false in such circumstances? Or maybe you meant to put the break in each catch?
Using a break when a valid integer is read isn't right, because it might be a negative integer, which your loop guard says you don't want.
This is basically the same as what your doing, I just tried to improve it a little bit by removing hardcoded values, made variables more descriptive, and included input validations.
final int ROW = 0;
final int COL = 1;
int coordinates[] = new int[2];
coordinates[ROW] = -1;
coordinates[COL] = -1;
boolean isInputValid = true;
Scanner scanner = new Scanner(System.in);
do {
try {
System.out.print("Please enter a valid row number:\t");
coordinates[ROW] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false; //if the input is not int
}
} while (!isInputValid && (coordinates[ROW] < 0) //do this until the input is an int
|| (coordinates[ROW] > R)); //and it's also not less than 0 or greater than R
//same logic applies here
do {
try {
System.out.print("Please enter a valid col number:\t");
coordinates[COL] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false;
}
} while (!isInputValid && (coordinates[COL] < 0)
|| (coordinates[COL] > C));
Hope this helps.
Related
In my task I need to put InputMismatchException when user tries to enter some values. User get some numbers from 1 to some number (simptoms.lenght).
int number=0;
do{
System.out.printf("Choose %d simptoms: \n", number+1);
for(int j=0; j< simptomi.length;j++){
System.out.printf("%d. %s %s\n", j + 1, simptoms[j].getName(),
simptoms[j].getValue());
}
System.out.print("Choose: ");
while(!scanner.hasNextInt()){
System.out.println("Please enter number!");
scanner.next();
}
number=scanner.nextInt();
scanner.nextLine();
if(number<0 || number> simptoms.length){
System.out.println("Error, choose again");
}
}while(number<0 || number> simptoms.length);
After this code I tried to do this:
instead of while(!scanner.hasNextInt()) I tried with try and I get this message:
Declaration, final or effectively final variable expected.
Is this the right way of replacing while loop or I should try to add something else.
I'm thinking about boolean = false and somehow try with that but I don't understand how to implement it properly.
I tried this:
try{
number=scanner.nextInt();
scanner.nextLine();
}
catch (InputMismatchException ex){
System.out.println("Please, enter number!");
}
Try it out! hope it helps!
try {
do {
number = scanner.nextInt();
if (!Character.isAlphabetic(number)) {
if (number > simptoms.length) {
System.out.println("Error, choose again");
System.out.println("Please enter number!");
}
}
} while (number != -1);
} catch (InputMismatchException e) {
System.out.println("Enter number");
}
I've been sitting here (embarrassingly) for hours trying to get a do-while loop to to accept user input until it's valid, but I seem to be messing up when it comes to the boolean that I'm using to try and exit the loop. Whenever I can get the program to partially work the catch exception just ends up repeating itself infinitely.
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
boolean valid = false;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
valid = false;
if (wallHeight <=0) {
throw new Exception ("Invalid Input");
}
}
catch (Exception e) {
System.out.println("Invalid Input");
}
} while (!valid);
Start by assuming the input is valid (and set valid to true on every iteration of the loop). Only set valid to false when you encounter an exception (hopefully the one you raised).
do {
valid = true;
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Exception("Invalid Input");
}
} catch (Exception e) {
valid = false;
System.out.println("Invalid Input");
}
} while (!valid);
Note that you do not appear to need an exception here, as
do {
valid = true;
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
System.out.println("Invalid Input");
valid = false;
}
} while (!valid);
would also work. Of course, that assumes the user only inputs valid double(s). If you need handle arbitrary input, you should check that there is a double before you attempt to consume it (and you must consume anything that isn't a double or you have an infinite loop). Like,
do {
valid = true;
System.out.println("Enter wall height (feet): ");
if (scnr.hasNextDouble()) {
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
System.out.println("Invalid Input");
valid = false;
}
} else {
System.out.println("Invalid Input " + scnr.nextLine());
valid = false;
}
} while (!valid);
Here is another take.I just moved the code that sets valid = true after the if check. It can make it that far only when its valid. Otherwise valid will be false and it will loop.
public class BasicDoWhile {
public static void main(String[] args) {
double wallHeight = 0.0;
boolean valid = false;
Scanner scnr = new Scanner(System.in);
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Exception("Invalid Input");
}
valid = true;
}
catch (Exception e) {
System.out.println("Invalid Input");
}
} while (!valid);
}
}
This is a guessing game. I want to enter user input after error message but my catch phrase keeps on printing infinitely.. please help me.
if I enter letter it will print
"Invalid Number! Try again."
"Invalid Number! Try again."
"Invalid Number! Try again."
"Invalid Number! Try again."
import java.util.*;
public class RandomGame {
public static Scanner sc = new Scanner(System.in);
public static void main(String args[]) {
Random rand = new Random();
int x = rand.nextInt(50);
int counter = 0;
int y;
boolean flag = false;
System.out.print("Give a number from 1-50:");
while(!flag) {
flag = true;
try {
y = sc.nextInt();
if (y < x) {
counter++;
System.out.println("Too low. Try again");
flag = false;
} else if (y > x) {
counter++;
System.out.println("Too high. Try again");
flag = false;
} else if (x == y) {
counter++;
System.out.println("you got it " + counter + " attempt(s):");
flag = true;
}
} catch(InputMismatchException | NumberFormatException e1) {
System.out.println("Invalid Number! Try again.");
}
flag = false;
}
System.out.println(x);
}
}
Your problem is that nextInt doesn't remove the offending character from the stream, so you keep encountering the same error over and over.
You'd be better to call next instead of nextInt, then try to parse the resulting String into an int, using Integer.parseInt. That way, if the content of the stream is non-numeric, it will actually be removed from the stream.
For this kind of things you can also use the "finally" close,
try{}
catch(Exception e){}
finally{}
finally always works (even if there wasn't any exception), even if there is any exception
and it helps the program works even if there was an error.
Hopeing someone can help. Been trawling for days and cant find a solution. Trying to create a while loop with a try/throw/catch for exception handling, but need to catch multiple exceptions.
I've tried just about everything I can think of it either doesn't come out the loop or it skips the rest of the code (not pasted here) and finishes the program.
Scanner scanner = new Scanner(System.in);
boolean NotCorrectInput = false;
howManyToAdd = 0;
while (!NotCorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
NotCorrectInput = true;
}
catch (InputMismatchException e){
System.err.println("You have not entered the correct number format. Please try again.");
}
try {
if (howManyToAdd < 1) {
throw new NegativeArraySizeException();
}
}
catch (NegativeArraySizeException e) {
System.err.println("You have not entered a possitive number. Please try again.");
}
}
SecondProduct lp[] = new SecondProduct[howManyToAdd];
//Rest of code from here on down.
I would like it to expect an int but if it is passed a double or a float then it will handle that in the loop and keep going until it is passed an int, but also if it is given a negative number to start off the array then it will loop back to the start and ask for a positive int to be passed.
You don't need to throw any exception :
while (!NotCorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
if (howManyToAdd >= 1)
NotCorrectInput = true;
else
System.err.println("You have not entered a positive number. Please try again.");
}
catch (InputMismatchException e) {
System.err.println("You have not entered the correct number format. Please try again.");
scanner.next();
}
}
BTW, NotCorrectInput is a confusing name, since you actually set it to true when the input is correct.
while (!NotCorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
NotCorrectInput = true;
if (howManyToAdd < 1) {
System.err.println("You have not entered a possitive number. Please try again.");
}
}
catch (InputMismatchException e){
System.err.println("You have not entered the correct number format. Please try again.");
}
}
Thats how you do multiple try catch!
Just adjust your code a bit:
Scanner scanner = new Scanner(System.in);
boolean CorrectInput = false;
howManyToAdd = 0;
while (!CorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
if (howManyToAdd < 1) {
throw new NegativeArraySizeException();
}
else
CorrectInput = true;
}
catch (InputMismatchException e){
System.err.println("You have not entered the correct number format. Please try again.");
}
catch (NegativeArraySizeException e) {
System.err.println("You have not entered a possitive number. Please try again.");
}
}
I have this piece of code:
do {
try {
input = sc.nextInt();
}
catch(Exception e) {
System.out.println("Wrong input");
sc.nextLine();
}
}
while (input < 1 || input > 4);
Right now, if I input 'abcd' instead of integer 1-4, it gives message "Wrong Input" and the program loops, how can I make it so that it also gives "Wrong Input" when I entered integer that doesn't fulfill the boolean (input < 1 || input >4)?
So that if I entered 5, it will also give me "Wrong Input".
Add this:
if(input < 1 || input > 4) {
System.out.println("Wrong input");
}
after input = sc.nextInt();
As of now, your try-catch block is checking if input is an int type. The do-while loop is checking input after it has been entered, so it is useless. The condition must be checked after the user enters what he/she wants. This should fix it:
do
{
try
{
input = sc.nextInt();
if(input < 1 || input > 4) // check condition here.
{
System.out.println("Wrong input");
}
}
catch(Exception e)
{
System.out.println("Expected input to be an int. Try again."); // tell user that input must be an integer.
sc.nextLine();
}
} while (input < 1 || input > 4);
You can also do this:
while (true) {
try {
input = sc.nextInt();
if (input >= 1 && input <= 4) {
break;
}
} catch (Exception e) {
System.out.println("Wrong input");
}
sc.nextLine();
}