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();
}
Related
How to catch an exception if the the input is string instead of integer?
It's confusing me since they used Try, Catch, Finally which looks new to me. Please enlighten me thanks.
import java.util.*;
public class ExceptionSample {
public static void main (String[]args){
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
System.out.print("Enter dividend: ");
dividend = s.nextInt();
System.out.print("Enter divisor: ");
divisor = s.nextInt();
try {
quotient = dividend/divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
}
}
}
It would go something like this:
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
while (true) {
System.out.print("Enter dividend: ");
try {
dividend = s.nextInt();
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Dividend Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
while (true) {
System.out.print("Enter divisor: ");
try {
divisor = s.nextInt();
if (divisor == 0) {
throw new java.util.InputMismatchException();
}
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Divisor Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
try {
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
s.close();
}
When the Scanner#nextInt() method is used and one or more alpha characters are supplied a InputMismatchException is thrown. We trap this exception and use it to our advantage for validating the numerical input.
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 want the program to retry the "try" part of the code every time the input is incorrect and throws an error(which is solved with an exception).
My code looks like this:
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
}catch(Exception e){
System.out.println("Incorrect input!");
My "makeHumanMove" function checks, if the number is from 1 to 3.. But if the user inserts a letter, it would throw an error and if it happens, I want the program to ask for another input until the user inserts a correct input.
I've tried while and for loops but I keep messing up. Any ideas?
How's about this code:
while (true) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
break;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Make sure that your makeHumanMove(enteredNumber); throws new Exception();
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
inputIsCorrect = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
This, of course, assumes that your makeHumanMove method throws an exception.
If I was doing this, I don't think I would be using exceptions. My code would be more like ...
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
inputIsCorrect = makeHumanMove(enteredNumber);
}
I'd change the makeHumanMove return a value that indicates whether the the inout is valid or not, rather than using exceptions. ( Can't remember if scanner.nextInt() throws exception .... )
Use a boolean value outside, set it to true at the end of the try block. Then you can test for it using a while loop.
int enteredNumber;
boolean correctNumber = false;
while (!correctNumber) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
correctNumber = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Note that you should not use exceptions at all to report incorrect input. You should test for incorrect input and abort early. You should also consider if makeHumanMove should actually be part of the try/catch block; input validation should not be part of the business logic of your application.
final int number;
System.out.print("Enter a number from 1 to 3: ");
while (true) {
int enteredNumber;
try {
enteredNumber = userInputScanner.nextInt();
} catch (Exception e) {
System.out.print("Not a number, enter a number from 1 to 3: ");
userInputScanner = new Scanner(System.in);
continue;
}
if (enteredNumber < 1 || enteredNumber > 3) {
System.out.print("Incorrect number, enter a number from 1 to 3: ");
continue;
} else {
number = enteredNumber;
break;
}
}
makeHumanMove(number);
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.
Just a little confused as to what is happening here. The point of this error trap is, for example, the user inputs 3 numbers/letters instead of a 4 digit number. This error trap was designed loop the question until the user gets it right. However it instead loops the error message. Can anyone give some pointers as to what is going on?
JFrame Error = new JFrame ();
String input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
while (true){
try{
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
You need to move code for ask the input to the loop.
JFrame Error = new JFrame ();
String input = null;
while (true){
try{
input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
As JacobM mentioned, you need to ask for the input inside the while loop. When the catch clause terminates, the next thing your code does will be the first thing in the while loop.
JFrame Error = new JFrame ();
while (true){
String input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
try{
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
You need to ask for a new value, inside the loop. change it to:
String input;
try {
while (true){
input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}