Java try-catch inside of a do-while loop - java

In my Java code shown below, I'm accepting user input of two doubles, and wrapping those values in a try-catch that handles an InputMismatchException. I've also wrapped a do-while loop around this try-catch block. I'm trying to craft the code in a way that handles the case where if a user inputs the wrong type for "number2", then the loop doesn't start over and ask the user to input "number1" all over again. I've been scratching my head on the best way to implement this and am open to any feedback or suggestions.
So the test case would be; the user inputs the right type for number1, but the wrong type for number2, in which case, how can I implement the code so that it only asks for re-entry of number2 instead of re-starting the entire loop. I've tried nested try-catch, nested do-whiles, etc. Any thoughts?
import java.util.InputMismatchException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
System.out.println("You've entered the numbers " + number1 + " " + number2);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
} while (continueInput);
}
}

You can extract method which takes Supplier
private <T> T executeWithRetry(String initialText, String retryText, Supplier<T> supplier) {
System.out.println(initialText);
while (true) {
try {
return supplier.get();
} catch (InputMismatchException ex) {
System.out.println(retryText);
}
};
}
And use it like
double number1 = executeWithRetry(
"Enter your first number: ",
"Try again, a double is required.",
() -> input.nextDouble()
)

Just split the process of reading the 2 values apart. This way you can individually check if an InputMismatchException occurs and handle it individually for each variable.
continueInput = false;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);
continueInput = false;
do {
try {
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);

try this,
Scanner input = new Scanner(System.in);
boolean continueInput = true;
double number1 = 0;
while (continueInput) {
try {
System.out.print("Enter your first number: ");
number1 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
continueInput = true;
double number2 = 0;
while (continueInput) {
try {
System.out.print("Enter your second number: ");
number2 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
System.out.println("You've entered the numbers " + number1 + " " + number2);

Related

How would I make it so that whenever a non-integer value is entered, it will tell the user to enter an integer value? Java - NetBeans

I'm making a very simple program that asks a user to input an age and then it will calculate a charge for admission. So far all works well but I'm wanting to add a check in so that if the user inputs anything other than an int value, it will ask them to enter an int value. I.e if they enter a character.
Here is my code:
public class CalcChargeAge {
public static void main(String[] args) {
int x;
double chargeA = 20;
double chargeB = 10;
System.out.println("Enter Users age to calculate charge for entry. ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if (x >= 18) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeA);
} else if (x >= 12) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeB);
} else {
System.out.println("Users age is " + x);
System.out.println("User entry charge is free. Print admission ticket.");
}
}
}
You can use the Scanner.hasNextInt() method to check whether the input is an integer, which I think is a lot nicer than catching an exception.
Then for the full implementation you could wrap everything in a loop, so you could do something like:
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
if(in.hasNextInt()) {
int x = in.nextInt();
// Handle input
break;
}
else {
// Handle invalid input
in.next();
}
}
Something like this should work fine:
boolean isValid = false;
int validInput = 0;
while (!isValid) {
try {
validInput = scanner.nextInt();
isValid = true;
}
catch (Exception e) {
System.out.println("Please enter a valid integer.");
}
}
// ... code using validInput
One of the ways (beware, it might not be the best or even the good one) to go about it would be to replace x=in.nextInt(); with
while(true) {
String input = in.next();
try {
x = Integer.parseInt(input);
break;
} catch (Exception e) {
System.out.println("Please provide an integer!");
}
}
this will not leave the loop until user provides an integer value (evil!)

Exception Handling for no user input in Java

I am trying to get my program to exception handle for if the user inputs nothing so they will get an error message of "Error, enter a dollar amount greater than 0" or "Error, Enter a 1, 2 or 3". As of now, the program does nothing if the user just hits "enter" with no input....
import java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Candleline
{
public static void main(String[] args)
{
//initiate scanner
Scanner input = new Scanner(System.in);
System.out.println("\tCandleLine - Candles Online");
System.out.println(" ");
//declare variables and call methods
double candleCost = getCandleCost();
int shippingType = getShippingType();
double shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandleCost()
{
//get candle cost and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
double candleCost = 0;
while(!done)
{
System.out.print("Enter the cost of the candle order: ");
try
{
inputCost = input.next();
candleCost = Double.parseDouble(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (candleCost <=0) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
}
return candleCost;
}
public static int getShippingType()
{
//get shipping type and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
int shippingCost = 0;
while(!done)
{
System.out.println(" ");
System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: ");
try
{
inputCost = input.next();
shippingCost = Integer.parseInt(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println(" ");
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
}
return shippingCost;
}
public static double getShippingCost(double candleCost, int shippingType)
{
//calculate shipping costs
double shippingCost = 0;
if (shippingType == 1)
{
shippingCost = 16.95;
}
if (shippingType == 2)
{
shippingCost = 13.95;
}
if (shippingType == 3)
{
shippingCost = 7.95;
}
if (candleCost >= 100 && shippingType == 3)
{
shippingCost = 0;
}
return shippingCost;
}
public static void output(double fCandleCost, double fShippingCost)
{
//display the candle cost, shipping cost, and total
Scanner input = new Scanner(System.in);
DecimalFormat currency = new DecimalFormat("$#,###.00");
System.out.println("");
System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost));
}
}
Replace input.next();
with input.nextLine();
You can write a method that validates the input before proceeding. It can keep asking for inputs if user enters something that is not valid. E.g. below example demonstrates how to validate an integer input:
private static int getInput(){
System.out.print("Enter amount :");
Scanner scanner = new Scanner(System.in);
int amount;
while(true){
if(scanner.hasNextInt()){
amount = scanner.nextInt();
break;
}else{
System.out.println("Invalid amount, enter again.");
scanner.next();
}
}
scanner.close();
return amount;
}

Make a loop AND catch using Strings instead of ints? (java)

I'm trying to make a text based rock paper scissors. I want the player to choose what they want to play to, for example "best (user response/2 + 1) out of (user response)" then it asks for verification if they would like to play to that number. If they say yes it continues the game with that score, if no it loops back up and lets them choose another number and I have an else that reminds them they can either select yes or no. When they are originally asked, letters don't effect and they are asked to try again. On the second loop around (when you say no) if you enter a String instead of an Int it crashes. Here what I have.
System.out.println("Best of:");
String line = userIn.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
bestOf = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = userIn.nextLine();
}
System.out.println("Okay, so you want to play best " + (bestOf / 2 + 1) + " of " + bestOf + "?");
String response2 = userIn.nextLine();
while (true) {
if (response2.contains("n")) {
System.out.println("What do you wish to play to then, " + name + "?");
bestOf = userIn.nextInt();
response2 = "y";
} else if (response2.contains("y") || response2.contains("Y")) {
winScore = (bestOf / 2 + 1);
System.out.println("Okay, best " + (bestOf / 2 + 1) + " of " + bestOf + " it is!");
break;
} else {
System.out.println("That's not a valid response! Try again.");
response2 = userIn.nextLine();
}
}
Instead of using parseInt use the string, in other words the input take it as string (even if is a number) them use the function "isNumber" too check if the string the user put is a number if not, do a while
System.out.println("Best of:");
String line = userIn.nextLine();
String aux = line;
do{
if (line.length() > 0)
aux = line;
if(!isNumeric(aux)){
System.out.println("Please enter a number");
line = userIn.nextLine();
}
}while(!isNumeric(aux));
bestOf = Integer.parseInt(aux);
so
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
You can extract your loop as a method and use it in second case as well.
private Integer readInt(Scanner scanner){
String line = scanner.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
Integer result = Integer.parseInt(line);
return result;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = scanner.nextLine();
}
}
or even better:
private Integer readInt(Scanner scanner){
Integer result;
do{
try{
return scanner.nextInt();
} catch (InputMismatchException e){
scanner.nextLine();
System.out.println("Please enter a number");
}
} while (true);
}

try catch placement issue within program design?

I've put in the try catch as shown now the program still skips to the 2nd & 3rd input question without printing the error exception after ("Enter your operation: add, subtract, divide, multiply, or exit"). Also if "exit" is inputed for first question the the 2nd & 3rd input requirements still loop before program finishes, is there any way to exit immediately as prompted with the other inputs being required?
Any suggestions welcome
import java.util.Scanner;
import java.io.*;
class Monday {
public static void main(String[] args) {
double n1,n2;
boolean check = true;
while(check) {
System.out.println("Enter your operation: add, subtract, divide, multiply, or exit");
Scanner myScan = new Scanner(System.in);
String op = myScan.next();
try {
System.out.println("Enter your 1st number");
try {
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();
} catch (Exception e) {
System.out.println("This is my error");
return;
}
/* System.out.println("Enter your 1st number");
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();*/
switch (op) {
case"add":
System.out.println("Your answer is "+ (n1 + n2));
break;
case"subtract":
System.out.println("Your answer is "+ (n1 - n2));
break;
case"divide":
System.out.println("Your answer is "+ (n1 / n2));
break;
case"multiply":
System.out.println("Your answer is "+ (n1 * n2)) ;
break;
case"exit":
System.out.println("Goodbye!");
break;
}
if ("exit".equals(op))
check = false;
} catch (Exception e) {
System.out.println("This is my error");
System.exit(1);
}
}
}
}
You don't even need try/catch.
double n1, n2;
System.out.println("Enter your 1st number");
if (myScan.hasNextDouble()) n1 = myScan.nextDouble();
else return;
System.out.println("Enter your 2nd number");
if (myScan.hasNextDouble()) n2 = myScan.nextDouble();
else return;
But if you want to use it:
double n1, n2;
System.out.println("Enter your 1st number");
try {
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();
} catch (Exception e) {
System.out.println("This is my error");
return;
}

How to go back to a particular point from a caught exception in java

public void processing()
{
System.out.println("Please enter the amount of saving per month: ");
try
{
while(input.hasNext())
{
setSavingPermonth(input.nextDouble());
System.out.println("Please enter expected interest rate: ");
setInterestRate(input.nextDouble());
System.out.println("Please enter number of month for saving: ");
setNumberOfMonth(input.nextInt());
displayInputs();
System.out.println();
totalContibution();
totalSavingAmount();
System.out.println();
System.out.println("\nPlease enter the amount of saving per month: \n(or <Ctrl + D> to close the program)");
}
}
catch(InputMismatchException inputMismatchException)
{
System.err.println("Input must be numeric. \ntry again: ");
//**Anything need to done here in order to go back to setInterestRate()?**
}
}
I want to go back to where before the exception caught the mis-input exception, for example, I type in a string for the setInterestRate(), but Java catches me there, and display the error message, question: how can I go back to there so that I can re-enter a correct data ?
Rewrite your code so it uses the following method:
static double inputDouble(Scanner input) {
while (input.hasNext()) try {
return input.nextDouble();
}
catch (InputMismatchException e) {
System.out.println("Wrong input. Try again.");
input.next(); // consume the invalid double
}
throw new IOException("Input stream closed");
}
You can use the following two methods to obtain integer and double:
static int getIntInput(Scanner input) {
while(true)
{
try {
if (input.hasNext()) {
return input.nextInt();
}
} catch (InputMismatchException e) {
System.err.println("Input must be numeric. \ntry again: ");
input.next();
}
}
}
static double getDoubleInput(Scanner input) {
while(true)
{
try {
if (input.hasNext()) {
return input.nextDouble();
}
} catch (InputMismatchException e) {
System.err.println("Input must be numeric. \ntry again: ");
input.next();
}
}
}

Categories