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;
}
Related
This is my code. I want to check if the input is either double or int.. it doesn't throw an error but it also doesn't work like I wanted it to be. Any help will be appreciated. the code was not yet finished please dont mind the computation.. (Sorry for my grammar)
import java.util.Scanner;
class HelloWorld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double number1 = 0;
double numb2 = 0;
int number3 = 0;
try{
System.out.println("Please enter the amount to be deposited each month: ");
String num1 = scan.nextLine();
System.out.println("Please enter the annual interest rate: ");
String num2 = scan.nextLine();
System.out.println("Please enter the month you plan to save: ");
String num3 = scan.nextLine();
if(scan.hasNext()){
number1 = Double.parseDouble(num1);
numb2 = Double.parseDouble(num2);
}
else{
System.out.println("Invalid response! Please enter a number. /n");
}
if(scan.hasNext()){
number3 = Integer.parseInt(num3);
}
else{
System.out.println("Invalid response! Please enter a number. /n");
}
double ans = number1 + numb2 + number3;
System.out.println(ans);
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
I also try doing this but it does the same.
if(scan.hasNextDouble() || scan.hasNextInt()){
number1 = Double.parseDouble(num1);
numb2 = Double.parseDouble(num2);
number3 = Integer.parseInt(num3);
}else{
System.out.println("Invalid response! Please enter a number. /n");
}
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);
I've made a basic calculator program and I'm getting this exception:
java.util.InputMismatchException
java.util.Scanner.next(Unknown Source)
The code runs just fine but when exception occurs it doesn't allows the user to input using Scanner. What am I doing wrong and how can I fix it?
package string;
import java.util.Scanner;
import java.lang.Exception;
public class Calculator {
double sum(double a,double b)
{
double c =a+b;
return c;
}
double subtract(double a,double b)
{
double c= a-b;
return c;
}
double multiply(double a,double b)
{
double c=a*b;
return c;
}
double divide(double a,double b)
{
double c=a/b;
return c;
}
public static void main(String[] args) {
Calculator f= new Calculator();
int choice;
int z;
Scanner s1 =new Scanner(System.in);
do{
try{
System.out.println("Welcome To Mini Calculator: Which Function Do You Want To Use");
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("4.Division");
System.out.println();
System.out.print("Please Enter Your Choice Number: ");
choice = s1.nextInt();
System.out.println();
switch(choice){
case 1:
System.out.print("Please Enter The First Number: ");
double x= s1.nextDouble();
System.out.println();
System.out.print("Please Enter The Second Number: ");
double y= s1.nextDouble();
double u = f.sum(x,y);
System.out.println();
System.out.println("The Sum Of Two Numbers is: " + u);
break;
case 2:
System.out.print("Please Enter The First Number: ");
double q= s1.nextDouble();
System.out.println();
System.out.print("Please Enter The Second Number: ");
double w= s1.nextDouble();
double i= f.subtract(q,w);
System.out.println();
System.out.println("The Substraction Of Two Numbers is: "+i );
break;
case 3:
System.out.print("Please Enter The First Number: ");
double e= s1.nextDouble();
System.out.println();
System.out.print("Please Enter The Second Number: ");
double r= s1.nextDouble();
double o= f.multiply(e, r);
System.out.println();
System.out.println("The Multiplication Of Two Numbers " + o);
break;
case 4:
System.out.print("Please Enter The First Number: ");
double t= s1.nextDouble();
System.out.println();
System.out.print("Please Enter The Second Number: ");
double k= s1.nextDouble();
double p= f.divide(t,k);
System.out.println();
System.out.println("The Divison of Two Numbers is: "+ p);
break;
default:System.out.println();
System.out.println("Please Enter a Valid Choice from 1 to 4");
}
}
catch(Exception e) {
System.out.println("Input error: You have entered wrong input");
System.out.println("Please restart the program");
}
System.out.println();
System.out.println("Do You Want To perform Another Functionality?");
System.out.println("Press 1 to Continue and Press 2 to Terminate The Program");
z= s1.nextInt(); // Issue comes here. It runs fine without exception. When exception occurs in above code ,it doesn't take input and shows another exception
}
while(z==1);
System.out.println();
System.out.println("Thank You For Using Calculator");
s1.close();
}
}
When you enter a wrong input, it goes in the catch but the input is still here, so z= s1.nextInt(); throws another exception which is not catched and it crashes
So you need to read the input in the catch, to clear the scanner :
} catch (Exception e) {
System.out.println("Input error: You have entered wrong input");
System.out.println("Please restart the program");
s1.nextLine();
}
Also, you have a lot of code duplicate, and variable names which means nothing, this is not very good compare to standards, I would suggestsomething like this to replace your whole switch{ ... }
System.out.println();
System.out.print("Please Enter The First Number: ");
double numb1 = s1.nextDouble();
System.out.println();
System.out.print("Please Enter The Second Number: ");
double numb2 = s1.nextDouble();
double res;
String operation = "";
switch (choice) {
case 1:
res = f.sum(numb1, numb2);
operation = "Sum";
break;
case 2:
res = f.subtract(numb1, numb2);
operation = "Substraction";
break;
case 3:
res = f.multiply(numb1, numb2);
operation = "Multiplication";
break;
case 4:
res = f.divide(numb1, numb2);
operation = "Divison";
break;
default:
res = 0;
System.out.println();
System.out.println("Please Enter a Valid Choice from 1 to 4");
}
System.out.println();
System.out.println("The " + operation + " Of Two Numbers is: " + res);
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;
}
I am a little confused about how to implement System.exit(0); in my program. What I want to have happen is for the user to type the word "exit" and for the program to terminate. I would also like the program to return "0.0" when "clear" is entered, but I think I am having trouble working with my variables because num1 and num2 are doubles but I want "exit" and "clear" to be acceptable inputs, as well.
If anyone has any insight, that would be greatly appreciated. Here is my code:
package projectapcs;
/**
*
* #author Apple
*/
import java.util.Scanner;
public class ProjectAPCS {
public static void exit(int x){
}
public static void clear(int y){
}
public static void main(String[] args) {
double num1;
double num2;
char char1;
String operation;
Scanner input = new Scanner(System.in);
System.out.println
("Enter 'exit' to quit the calculator, 'help' for more options or 'continue' to use the calculator");
System.out.println
("\nEnter the first number:");
num1 = input.nextInt();
System.out.println
("Display:" + num1);
System.out.println("Please enter operation:");
operation = input.next();
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
if ("+".equals(operation)){
System.out.println((num1 + num2));
}
else if ("-".equals(operation)){
System.out.println((num1 - num2));
}
else if ("/".equals(operation)){
System.out.println((num1 / num2));
}
else if ("*".equals(operation)){
System.out.println((num1 * num2));
}
else if ("-x".equals(operation)){
System.out.println (-num1);
}
else if ("x^2".equals(operation)){
System.out.println (num1 * num1);
}
else if ("sqrt".equals(operation)){
System.out.println (Math.sqrt(num1));
}
else if ("H".equals(num1)){
System.out.println("Type + for the addition of values");
System.out.println("Type - for the substraction of values");
System.out.println("Type * for the multiplcation of values");
System.out.println("Type / for the division of values");
System.out.println("Type negate for the negation of values");
System.out.println("Type ^2 for squaring of values");
}
else if("E".equals(num1)){
System.out.println ("Calculator program terminated...");
System.exit(0);
}
}
}
If you want to allow arbitrary inputs, read input as a String, then convert to double as needed:
String input = scanner.next();
if (input.equals("exit")) {
exit();
else if (input.equals("clear")) {
clear();
} else {
try {
double number = Double.parseDouble(input);
/* do something with `number` */
} catch (NumberFormatException e) {
System.err.println("Not a double.");
}
}