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");
}
Related
I cannot quite figure out how to make my basic financial calculator be able to run a new set of numbers without closing the program. What I currently have allows me to run one set of numbers, and when I get to "Would you like to continue?", when I press 1 it simply will print "Would you like to continue?" however many times I press 1. Here is what I have so far:
package Register;
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
{
System.out.println("Electricity Bill: $" + total);
}
System.out.println("");
boolean keepLooping = true;
while (keepLooping) {
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}
You have used while loop around asking choice statements only. So use while loop at the beginning in main method as below:
import java.util.Scanner;
public class Register{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
boolean keepLooping = true;
while(keepLooping) {
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
System.out.println("Electricity Bill: $" + total);
System.out.println("");
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}
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;
}
Use a while loop to keep asking the user to enter the order of
numbers until the user does give two numbers in the right order (first
smaller than second
Hi! i'm a beginner in java and I have this code but I can't loop the "error" message. it just prints 2 times
import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if (num1 < num2) {
int counter = num1;
while (counter <= num2) {
System.out.print(counter + " ");
counter = counter + 1;
}
}
else {
System.out.println("Error: the first number must be smaller than the second");
System.out.print("Please type two numbers: ");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
}
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers");
System.out.printn("first number must be smaller than the second:)";
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if(num1>=num2) {
System.out.println("Error: First number must be smaller than the second.");
}
}