InputMismatchException in Java replacing while loop - java

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

Related

How to make my program have an outofbounds exception

I am trying to catch an outofbounds exception in my program that creates a random number from 1 to 50 and the user guesses that number. The problem that I am facing is that whenever I enter a number that is past the maximum it doesn't catch it as an exception and displays the appropriate message but instead displays a different message.
This is what I have currently
Scanner in = new Scanner(System.in);
int count = 0, ran, min = 1, max = 50;
int ent = 0;
ran = (int)(Math.random()*(max-min)) + min;
System.out.println("Guess a number from 1 to 50.");
try{
do{
ent = in.nextInt();
count++;
if(ent > ran){
System.out.println("Too high. Try again.");
}else if(ent < ran){
System.out.println("Too low. Try again.");
}
}while(ent!=ran);
}
catch(IndexOutOfBoundsException ex){
System.out.println("Guess a number from 1 to 50!");
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
}
I also want to continue the program even after catching an exception but whenever I try to change it the result ends in an infinite loop
boolean done = false;
while(!done){
System.out.println("Guess a number from 1 to 50.");
try{
ent = in.nextInt();
count++;
if(ent > ran){
System.out.println("Too high. Try again.");
}else if(ent < ran){
System.out.println("Too low. Try again.");
}
done = true;
}
catch(IndexOutOfBoundsException ex){
System.out.println("Guess a number from 1 to 50!");
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
}
}
this is what I tried to do
You should not employ Exceptions for flow control - use a loop with a if-condition that makes sense. You can bake it into the while-loop condition but in this case the return short-circuits the loop if the guess is valid.
public int getGuess(Scanner in) {
while (true) {
System.out.printf("Enter a value between %d and %d", min, max).println();
int guess = in.nextInt();
if (guess < min || guess > max) {
System.out.printf("Guess must be between %d and %d, try again", min, max).println();
} else {
return guess;
}
}
}

I want to check for both negative number and non-number

I have code to check for non numbers but also wish to include a check for negative numbers. If the number is negative or not a number, they have to re-enter info. I tried putting an if(depValue < 0).... after try{ and before catch but that didn't work. It doesn't make sense to me if I were to put the if statement after the while loop.
String depIn = "";
BufferedReader depositInput = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("Amount to deposit: ");
depIn = depositInput.readLine();
double depValue = 0.00;
try{
depValue = Double.parseDouble(depIn);
break;
}
catch(NumberFormatException ne){
System.out.println("You did not enter a number!");
}
}
You can break out of the loop when you have the number you need.
double depValue;
while(true){
System.out.print("Amount to deposit: ");
depIn = depositInput.readLine();
try {
if ((depValue = Double.parseDouble(depIn)) > 0)
break;
System.out.println("The number needs to be positive!");
} catch(NumberFormatException ne) {
System.out.println("You did not enter a number!");
}
}
Put it in the same try catch block, and just display the error message from the caught NumberFormatException
try{
depValue = Double.parseDouble(depIn);
if (depValue < 0) throw new NumberFormatException("Negative value not acceptable!");
break;
}
catch(NumberFormatException ne){
ne.printStackTrace();
}

Multiple try catch in a while loop

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

Endless loop with try and catch JAVA

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.

Exception in do while loop

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

Categories

Resources