Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Main.java (Main Class)
package com.indie;
import java.util.InputMismatchException;
import java.util.Scanner;
import static com.indie.Operations.*;
public class Main {
private static double Number1;
private static double Number2;
private static double Total;
private static String Symbol;
private static boolean noError;
private static boolean exceptioncaught;
public static void main(String[] args) throws InterruptedException{
noError = false;
while (!noError) {
exceptioncaught = false;
while (!exceptioncaught) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your number:");
try {
Number1 = scanner.nextDouble();
} catch (InputMismatchException ex) {
System.out.println();
System.out.println("TypeERROR: You didn't input a vaild number!");
exceptioncaught = true;
System.out.println();
Thread.sleep(3000);
break;
}
System.out.println("What do you want to do:");
Symbol = scanner.next();
if (!Symbol.contains("+") && !Symbol.contains("-") && !Symbol.contains("*") && !Symbol.contains("x") && !Symbol.contains("/") && !Symbol.contains("÷")) {
System.out.println();
System.out.println("TypeERROR: You didn't input a valid symbol!");
exceptioncaught = true;
System.out.println();
Thread.sleep(3000);
break;
}
System.out.println("Enter your second number:");
try {
Number1 = scanner.nextDouble();
} catch (InputMismatchException ex) {
System.out.println();
System.out.println("TypeERROR: You didn't input a vaild number!");
exceptioncaught = true;
System.out.println();
Thread.sleep(3000);
break;
}
System.out.println();
if (Symbol.contains("+")) {
Total = Add(Number1, Number2);
noError = true;
break;
} else if (Symbol.contains("-")) {
Total = Subtract(Number1, Number2);
noError = true;
break;
} else if (Symbol.contains("*") || Symbol.contains("x")) {
Total = Multiply(Number1, Number2);
noError = true;
break;
} else if (Symbol.contains("/") || Symbol.contains("÷")) {
Total = Divide(Number1, Number2);
noError = true;
break;
}
}
}
System.out.println(String.valueOf(Number1)
+Symbol+String.valueOf(Number2)
+"="+String.valueOf(Total));
}
}
Operations.java (2nd Class)
package com.indie;
public class Operations {
public static double Add(double x, double y) { return x+y; }
public static double Subtract(double x, double y){ return x-y; }
public static double Multiply(double x, double y){ return x*y; }
public static double Divide(double x, double y){ return x/y; }
}
Got this result
Any way of fixing it? How did it end up with 2.0+20.0=2.0? Please Help.
Any way of preventing it from giving that type of results?
Other results:
result 1:
Enter your number:
2
What do you want to do:
+5
Enter your second number:
56
56.0+50.0=56.0
result 2:
Enter your number:
1
What do you want to do:
+1
Enter your second number:
1
1.0+10.0=1.0
On this part of the code, you should change this:
...
System.out.println("Enter your second number:");
try {
Number1 = scanner.nextDouble();
}
...
to this:
...
System.out.println("Enter your second number:");
try {
Number2 = scanner.nextDouble();
}
...
You never change the value of Number2 in your code.
Something it is goood to have a second pair of eyes
In your code you never assign value to Number2
System.out.println("Enter your second number:");
try {
Number2 = scanner.nextDouble();
Related
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 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;
}
The only problem I'm having with my program is the scanner, I've used it many times but in this program it won't run right. The error is in the public static double getCandlecost() and the public static int getShippingType() methods. under the int shippingType = sc.nextInt(); and the double candleCost = sc.nextDouble(); both say "sc cannot be resolved" and in my main class I did declare it.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Candel {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double candleCost, shippingCost;
int shippingType;
candleCost = getCandlecost();
shippingType = getShippingType();
shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandlecost()
{
boolean done = false;
do{
try
{
System.out.print("Enter the cost of the candle order ");
double candleCost = sc.nextDouble();
done = true;
return candleCost;
} catch (InputMismatchException e)
{
System.out.println("Error, Enter a dollar amount greater than 0");
}
} while (!done);
return 0;
}
public static int getShippingType()
{
System.out.println("Enter the type of shipping: ");
System.out.println("1> Priority <overnight>");
System.out.println("2> Express <2 business days>");
System.out.println("3> Standard <3 to 7 business days>");
System.out.println("Enter type number: ");
int shippingType = sc.nextInt();
if(shippingType == 1){}
else if(shippingType == 2){}
else if(shippingType == 3){}
return shippingType;
}
public static double getShippingCost(double candleCost, int shippingType)
{
switch(shippingType)
{
case 1:
candleCost = 16.95 + candleCost;
break;
case 2:
candleCost = 13.95 + candleCost;
break;
case 3:
if (candleCost > 100.00){
candleCost = candleCost;
}
else{
candleCost = 7.95 + candleCost;
}
break;
}
return candleCost;
}
public static void output(double candleCost, double shippingCost)
{
DecimalFormat twoDigits = new DecimalFormat("$#,000.00");
System.out.println("The candle cost of " + twoDigits.format(candleCost) + " with shipping costs of "
+ shippingCost + " equals " + twoDigits.format(candleCost + shippingCost));
}
}
Your scanner is out of scope. Since you have declared it in the main() method, only that method can access it. Your scanner needs to be static as well. Write it like this instead:
public class Candel {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
...
}
...
}
I have this program that asks user to enter a value and it calculates it as the user like to initial value of zero, then it ask the user what process to do again and ask the user to enter a value again and it calculates it to the last value of the instance, the problem is every time it asks the user to enter value it calculates it to zero not to the last entry. Please help me find the bug:
The program has to has two classes, one for the calculator and the other for the methods:
FIRST CLASS
public class MainClass {
public static void main(String[] args) {
MemoryCalculator calc = new MemoryCalculator();
calc.getCurrentValue();
displayMenu();
}
public static int displayMenu() {
Scanner input = new Scanner(System.in);
int choice;
do {
System.out.println("Menu");
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Clear");
System.out.println("6.Quit");
System.out.println("");
System.out.println("What would you like to do?");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
return displayMenu();
}
} while (choice > 6 || choice < 1);
MemoryCalculator calc = new MemoryCalculator();
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
return displayMenu();
}
public static double getOperand(String prompt) {
return 0;
}
}
SECOND CLASS
public class MemoryCalculator {
private double currentValue;
public double getCurrentValue() {
System.out.println("The current value is " + currentValue);
return 0;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
currentValue -= operand2;
getCurrentValue();
}
public void multiply(double operand2) {
currentValue *= operand2;
getCurrentValue();
}
public void divide(double operand2) {
if (operand2 == 0) {
System.out.println("Sorry, you can not divide by 0");
}
currentValue /= operand2;
getCurrentValue();
}
public void clear() {
currentValue = 0;
getCurrentValue();
}
}
You probably want to keep the last value stored in "calc". I see 3 bugs.
Move this line before the start of your "do" loop. This will keep it from reseting the value inside this variable/class.
MemoryCalculator calc = new MemoryCalculator();
Move your ending "while" loop line to the bottom of your method(right before the return statement). It only appears to be working because in your return statement you are calling your method again...see #3. Also you will want to change the "or" to the "and" operator in the while statement "choice>6 && choice<1"
}while(choice>6 && choice<1);
In you displayMenu method change the return statement, because you don't want it to call itself in an infinite loop... now that the do while loop is fixed.
return displayMenu();
to this
return choice;
I am working on teaching myself java and while working on a code using classes I ran into this error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at StateCalculator.getOperand(StateCalculator.java:29)
at StateCalculator.main(StateCalculator.java:77)
Below is my code:
import java.util.Scanner;
public class StateCalculator {
private double currentValue = 0;
//Initialize to 0
public StateCalculator() {
}
public static int displayMenu() {
Scanner keyboard = new Scanner(System.in);
int menuChoice = 0;
do {
System.out.print("Menu\n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n 5.Clear\n 6. Quit\n What would you like to do?: ");
menuChoice = keyboard.nextInt();
} while(menuChoice < 1 || menuChoice > 6);
keyboard.close();
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
double operand = 0;
System.out.print(prompt);
operand = input.nextDouble();
input.close();
return operand;
}
public double getCurrentValue() {
return currentValue;
}
public void add(double operand) {
currentValue += operand;
}
public void subtract(double operand) {
currentValue -= operand;
}
public void multiply(double operand) {
currentValue *= operand;
}
public void divide(double operand) {
if(operand == 0) {
currentValue = Double.NaN;
}
else {
currentValue /= operand;
}
}
public void clear() {
currentValue = 0;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StateCalculator calculator = new StateCalculator();
int option;
double operand;
do{
System.out.println("The current value is " + calculator.currentValue);
option = StateCalculator.displayMenu();
switch(option) {
case 1:
operand = getOperand("What is the second number?: ");
calculator.add(operand);
break;
case 2:
operand = getOperand("What is the second number?: ");
calculator.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?: ");
calculator.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?: ");
calculator.divide(operand);
break;
case 5:
calculator.clear();
break;
}
}while(option != 6);
keyboard.close();
}
}
I tried running the debug feature in eclipse and discovered the problem occurs on line 29 in my getOperand method when I attempt to set operand = input.nextDouble. However, I don't understand why this would be an issue.
Don't call keyboard.close(); when you close keyboard (which you defined)
Scanner keyboard = new Scanner(System.in);
it closes System.in, and then your other methods can't work (because the console will not re-open). You can have multiple scanners on System.in (as long as you don't close them), or pass one (or, but please don't, use a global).
Per the javadoc,
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.