Right now, it loops infinitely on the catch after one error. How can I make it go back to the try after a catch? boolean condition is declared properly, no compilation errors or anything. The rest of the code in the class is kind of a mess as I'm waiting for an answer about the re-trying.
double base = 0;
double height = 0;
double area = 0;
boolean again = true;
while (again) {
try {
System.out.print("Enter the length of base of triangle in cm : ");
base = input.nextDouble();
again = false;
} catch (Exception ex) {
System.out.println("Invalid input");
input.next();
}
try {
System.out.print("Enter the length of height of triangle in cm : ");
height = input.nextDouble();
} catch (Exception ex) {
System.out.println("Invalid Input");
String next = input.next();
}
area = (base * height) / 2;
use hasNextDouble() instead of using try/catch exception since you are not explicitly catching InputMismatchException
while (again) {
// if the next is a double, print the value
if (input.hasNextDouble()) {
base = input.nextDouble();
System.out.println("You entered base: " + base);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}
}
again = true;
while (again) {
// if the next is a double, print the value
if (input.hasNextDouble()) {
height = input.nextDouble();
System.out.println("You entered height: " + height);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}
}
area = (base * height) / 2;
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.
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);
}
}
I need values inputted into the array to be from 1-100 and not any letters. I tried to set up a temporary value that will catch numbers that are not 1-100 before but can not seem to get it to work. I come to problems where the program will close if letters are inputted. Any help would be appreciated.
public class FocusGroup {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double tempValue = scan.nextDouble();
if (tempValue > 100 || tempValue < 0) {
scan.nextDouble();
System.out.println("Invalid");
} else {
while (true) {
try {
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = scan.nextDouble();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input");
scan.nextLine();
}
}
}
}
}
In your catch statements, you use scan.nextLine(), but you should use scan.nextDouble(), like you do in your main loop. That is, you want to accept doubles as input.
Also, your try/catch syntax seems to be wrong. You want to catch errors that can be caused by user input; therefore, you need to add the code where the user inputs something in the try block. See below:
try {
double tempValue = scan.nextDouble();
//this loop will keep spinning, until tempValue is valid
while (tempValue > 100d || tempValue < 0d) {
System.out.println("Invalid. Try again. Range is 0 - 100");
tempValue = scan.nextDouble();
}
//this loop will spin forever (There is nothing to terminate it)
while (true) {
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = scan.nextDouble();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input");
scan.nextDouble(); //this doesn't do anything. The value is not assigned to any variable
}
With the above code, when the user enters an invalid characters, e.g: an alphabet letter, then the program will stop. Why? Because the catch is outside the endless loop, which makes your program counter move outside the loop and when the code in the catch statement is executed, your program will also terminate as it reached the end.
What you can do, is something like this:
static double validValueWithRange(Double min, Double max){
Scanner s = new Scanner(System.in);
System.out.println("Enter a valid value for a 'double': ");
double value;
try {
value = s.nextDouble();
if(value > max || value < min){
System.out.println("Invalid. Try again. Range is 0 - 100");
return validValueWithRange(min, max);
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Try again.");
return validValueWithRange(min, max);
}
return value;
}
static double validValue(){
Scanner s = new Scanner(System.in);
System.out.println("Enter a valid value for a 'double': ");
double value;
try {
value = s.nextDouble();
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Try again.");
return validValue();
}
return value;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
double tempValue = validValueWithRange(0d, 100d);
while (true) {
System.out.println("Now entering endless while loop");
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = validValue();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
}
You just have to put the initialization of the variable in a try and catch block like this:
try {
double tempValue = scan.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Please enter a number.");
}
I am having an issue where it isn't checking the validity of user input correctly. It breaks if I input a letter or string as a choice instead of looping through and asking again. I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement. Advice?
public class Main
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
displayMenu();
int entryChoice = scan.nextInt();
while (entryChoice != 9)
{
System.out.println(userSelection(entryChoice));
displayMenu();
isInt(entryChoice);
entryChoice = scan.nextInt();
}
scan.close();
System.exit(0);
}
public static boolean isDouble(double x)
{
double userInput = x;
try
{
userInput = Double.parseDouble(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input. Try again.");
return false;
}
}
public static boolean isInt(int x)
{
int userInput = x;
try
{
userInput = Integer.parseInt(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input");
return false;
}
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice)
{
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6)
{
System.out.println("Enter one number: ");
x = scan.nextDouble();
}
else
{
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
}
switch (entryChoice)
{
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0)
{
System.out.println("Can't divide by zero. Please enter another number.");
y = scan.nextDouble();
result = x / y;
}
else
{
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
//store a number
break;
case 8:
//recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement.
You don't.
Your isInt() method ignores its parameter, reads a new value from the scanner and checks to see if it's a number, and doesn't return the new value, whether or not it's a number.
In any case, the Scanner class you are using to collect user input already does this sort of validation for you. You started in the correct direction with
int entryChoice = scan.nextInt();
but it's dangerous to try to get a token from a Scanner without first checking to see if it has one for you to get.
If you look at the API docs for Scanner, you'll see a whole list of nextFoo() and hasNextFoo() methods. These are meant to be used together.
Generally what you want is a loop which prompts the user for the desired input until they give it, like this:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (!scan.hasNextInt()) {
scan.next(); // throw away non-numeric input
System.out.println("Please enter a number");
}
System.out.println("User entered: " + scan.nextInt());
This will end up re-prompting the user until they give you a number:
Please enter a number
apple
Please enter a number
fox
Please enter a number
bear
Please enter a number
42
User entered: 42
Here is your code,However i did many changes.Wish this help you little.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static int entryChoice = 0;
static boolean tester = true;
static double result;
public static void main(String[] args) {
displayMenu();
boolean check = isInt(entryChoice);
while (check && entryChoice != 9) {
result = userSelection(entryChoice);
System.out.print(result == 0 && !tester ? "" : result + "\n");
if (!tester)
break;
}
scan.close();
System.exit(0);
}
/*
* public static boolean isDouble(double x) {
*
* try { x = Double.parseDouble(scan.next()); return true; } catch
* (NumberFormatException ignore) { System.out.println(
* "Invalid input. Try again.");
*
* return false; } }
*/
public static boolean isInt(int x) {
try {
x = Integer.parseInt(scan.next());
entryChoice = x;
return true;
} catch (NumberFormatException ignore) {
System.out.println("Invalid input");
System.err.println("program will be terminated!");
tester = false;
return false;
}
}
public static void displayMenu() {
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice) {
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6) {
try {
System.out.println("Enter one number: ");
x = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.out.println("Invalid input");
}
} else {
try {
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.err.println("Invalid input,program will be terminated !");
tester = false;
// return ;
}
}
switch (entryChoice) {
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0 && tester) {
System.out.println("Can't divide by zero. Please enter another number.");
try {
y = scan.nextDouble();
} catch (InputMismatchException ex) {
System.err.println("invalid input, program will be terminated");
tester = false;
}
result = x / y;
} else if (tester) {
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
// store a number
break;
case 8:
// recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
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.