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);
Related
I am trying to program a menu for my calculator. I do not know how to get out of my inner loop and get back to my outer loop once I have executed the inner loop. I have to finish the whole case of the inner loop before I can get back to the outer loop. Is there a way that I can go back and forth of the nested switch whenever I want to? and when I execute my outer switch case 3, it executes infinitely. Maybe because it's inside a loop.
import java.util.Scanner;
public class MainInterface {
static Scanner input = new Scanner(System.in);
static boolean hasRun = false;
public static void main(String args[])
{
Calculator Mycal = new SimpleCalculator();
ScientificCalculator Mycal2 = new ScientificCalculator();
mainMenu();
int choice = input.nextInt();
do {
System.out.println("\n");
switch(choice) // outer switch
{
case 1: simpleCalculatorMenu();
int choice2 = input.nextInt();
switch(choice2) // inner switch
{
case 1: //ADDITION
System.out.println("ADDITION");
System.out.println("\n");
System.out.println("Enter first number: ");
float x = input.nextFloat();
System.out.println("Enter second number: ");
float y = input.nextFloat();
System.out.println("\n");
System.out.println("The sum of " + x + " " + y + " is " + Mycal.add(x, y));
System.out.println("\n");
System.out.println("Would you like to return to the main menu?");
System.out.println("\n");
System.out.println("Enter 1. to return 2. to exit");
choice = input.nextInt();
break;
}
break;
case 2: System.out.println("SCIENTIFIC CALCULATOR");
System.out.println("\n");
System.out.println("1. power(x, pow) 2. sin(xDeg) 3. cos(xDeg) 4. tan(xDeg)");
System.out.println("\n");
System.out.println("5. pi() 6. fact(x) ");
int choice3 = input.nextInt();
switch(choice3) {
case 1:
System.out.println("POWER");
System.out.println("\n");
System.out.println("Enter first number: ");
double x = input.nextDouble();
System.out.println("Enter second number: ");
double y = input.nextDouble();
System.out.println("\n");
System.out.println("The power of " + x + " to the power of " + y + " is " + Mycal2.power(x, y));
System.out.println("\n");
System.out.println("Would you like to return to the main menu?");
System.out.println("\n");
System.out.println("Enter 1. to return 2. to exit");
choice = input.nextInt();
break;
case 2:
}
break;
case 3: mainMenu();
break;
case 4: System.exit(choice);
break;
}
} while(choice != 0);
}
public static void simpleCalculatorMenu () {
System.out.println("SIMPLE CALCULATOR");
System.out.println("\n");
System.out.println("1. Addition 2. Subtraction 3. Multiplication 4. Division");
System.out.println("\n");
System.out.println("5. Squared Root 6. Squared 7. Cube 8. Discount ");
}
public static void mainMenu () {
System.out.println("What calculator do you want to use?");
System.out.println("\n");
System.out.println("1. Simple Calculator \t 2. Scientific Calculator");
}
}
by adding label you can try like this
OUTER:
switch(condition1) {
case x:
switch(condition2) {
case y:
System.out.println("hello");
break OUTER;
}
}
I made a program which should display an equation after choosing a type of algebra equation which doesn't works for some reason.
I have tried changing the scanners name but it just displays Wrong choice when an expression is chosen.
I would really appreciate it if you can help me thank you.
This is the code:
/** WAP using switch case to print the following :
1. 3X+4Y+Z
2. 3A^2+4B^3+3C*/
import java.util.*;
class F
{
public static void main(String a[])
{
Scanner in = new Scanner(System.in);
System.out.println("Algebra Program executed : No. to be typed: ");
System.out.println(" (i) 3X+4Y+Z 1 ");
System.out.println(" (ii) 3A^2+4B^3+3C 2 ");
int ch = in.nextInt();
switch(ch)
{
//Program 1
case '1': Scanner sc = new Scanner(System.in);
System.out.println("Type a number for X...");
int X = sc.nextInt();
System.out.println("Type a number for Y...");
int Y = sc.nextInt();
System.out.println("Type a number for Z...");
int Z = sc.nextInt();
int sum = (3*X)+(4*Y)+Z;
System.out.println(" ");
System.out.println("Value of X is "+X);
System.out.println("Value of Y is "+Y);
System.out.println("Value of Z is "+Z);
System.out.println("Value of 3X+4Y+Z is "+sum);
break;
//Program 2
case '2': Scanner hi = new Scanner(System.in);
System.out.println("Type a number for A...");
double A = hi.nextDouble();
System.out.println("Type a number for B...");
double B = hi.nextDouble();
System.out.println("Type a number for C...");
double C = hi.nextDouble();
double pro = 3*Math.pow(A, 2) + 4*Math.pow(B, 3) + 3*C;
int isum = (int) pro;
System.out.println(" ");
System.out.println("Value of A is "+A);
System.out.println("Value of B is "+B);
System.out.println("Value of C is "+C);
System.out.println("Value of 3A^2+4B^3+3C is "+isum);
break;
//Else
default: System.out.println("Wrong Choice");
}
}
}```
You need to change the case to case 1 and case 2 instead of case '1' and case '2'.
Note that '1' and '2' are char literals; not the int literals. the ASCII value of '1' is 49 and that of '2' is 50.
i have a calculator class and i want the operation input to be specific to these strings "+, -, /, *" if its not, i want to print a message to enter the operator again.
and please if someone would lessen my code please do it. thanks
here is my code
import java.util.Scanner;
public class Calculator1 {
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
String operation;
Double fnum, lnum, answer;
System.out.println("Enter first Number: ");
while (!num.hasNextDouble())
{
num.next();
System.out.print("Enter first Number: ");
}
fnum = num.nextDouble();
System.out.println("Enter Operation: ");
//HERE IM BEING CONFUSED
while (!num.equals("+, -, /, *"))
{
num.next();
System.out.print("Enter Operator: ");
}
operation = num.next();
//End
System.out.println("Enter Second Number: ");
while (!num.hasNextDouble())
{
num.next();
System.out.print("Enter Second Number: ");
}
lnum = num.nextDouble();
switch (operation) {
case "+":
answer = fnum + lnum;
System.out.print("Equals= " + answer);
break;
case "-":
answer = fnum - lnum;
System.out.print("Equals= " + answer);
break;
case "*":
answer = fnum * lnum;
System.out.println("Equals= " + answer);
break;
case "/":
answer = fnum / lnum;
System.out.println("Equals= " + answer);
break;
default:
System.out.println("wrong operator");
break;
}
}
}
This is a way to use operators with SWITCH sentence.
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
double v1,v2;
String v3;
System.out.print("Enter first number: ");
v1 = num.nextDouble();
System.out.print("Enter second number: ");
v2 = num.nextDouble();
System.out.print("Enter operation [+] [-] [*] [/]: ");
v3 = num.next();
System.out.println( ("+".equals(v3) ) ? Operators.ADD.calculate(v1, v2) : "....");
}
public enum Operators {
ADD;
double calculate(double x, double y) {
switch (this) {
case ADD:
return x + y;
default:
throw new AssertionError("Unknown operations " + this);
}
}
}
I'm trying to make a calculator where the person can continue to put in numbers like "2+4*7-1" until they press = and then they will get the answer, and I have no idea how to even start. I know how to make a calculator with just 2 numbers but not how to have the user giving new numbers all the time. If anyone have any tips/code I could look at that would help a lot.
Check this Creating a Calculator using JFrame , and this is a step to step tutorial
yes yes i know that i am replying after 2 years but still maybe it will come in handy to other ppl in the future.
its a simple console code no gui.
So here's how i did it on eclipse
import java.util.Scanner;
public class Adv_calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int option;
double num1, num2, result;
result = 0;
do {
System.out.println("Welcome to The Calculator app");
System.out.println("Please Choose an option");
System.out.println("1) Add");
System.out.println("2) Subtract");
System.out.println("3) Multiply");
System.out.println("4) Continue");
System.out.println("5) Exit");
System.out.print("Option :: ");
option = sc.nextInt();
switch (option) {
case 1: {
System.out.println("Addition Calculator");
System.out.print("Kindly Enter the FIRST Number :: ");
num1 = sc.nextDouble();
System.out.print("Kindly Enter the SECOND Number :: ");
num2 = sc.nextDouble();
result = num1 + num2;
System.out.print("The Result is :: ");
System.out.println(result);
break;
}
case 2: {
System.out.println("Subtraction Calculator");
System.out.print("Kindly Enter the FIRST Number :: ");
num1 = sc.nextDouble();
System.out.print("Kindly Enter the SECOND Number :: ");
num2 = sc.nextDouble();
result = num1 - num2;
System.out.print("The Result is :: ");
System.out.println(result);
break;
}
case 3: {
System.out.println("Multiplication Calculator");
System.out.print("Kindly Enter the FIRST Number :: ");
num1 = sc.nextDouble();
System.out.print("Kindly Enter the SECOND Number :: ");
num2 = sc.nextDouble();
result = num1 * num2;
System.out.print("The Result is :: ");
System.out.println(result);
break;
}
case 4: {
System.out.println("Please Choose an option");
System.out.println("1) Add");
System.out.println("2) Subtract");
System.out.println("3) Multiply");
System.out.print("Option :: ");
option = sc.nextInt();
switch (option) {
case 1: {
System.out.println("Addition Calculator");
System.out.print("Kindly Enter the SECOND Number :: ");
num2 = sc.nextDouble();
result = result + num2;
System.out.print("The Result is :: ");
System.out.println(result);
break;
}
case 2: {
System.out.println("Subtraction Calculator");
System.out.print("Kindly Enter the SECOND Number :: ");
num2 = sc.nextDouble();
result = result - num2;
System.out.print("The Result is :: ");
System.out.println(result);
break;
}
case 3: {
System.out.println("Multiplication Calculator");
System.out.print("Kindly Enter the SECOND Number :: ");
num2 = sc.nextDouble();
result = result * num2;
System.out.print("The Result is :: ");
System.out.println(result);
break;
}
}
break;
}
case 5: {
System.out.println("Thank you for using my program :: ");
System.out.println("Program will now exit ");
System.exit(0);
}
}
} while (option != 5);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I know these must be basic errors, but I'm not sure how to fix them.
I changed my class name to Interface & now Java has a problem with it.
Also, in my switch statement, I've tried to call the enterData method, but I'm getting an error on this line as well as on this line... "private static void enterData()" <-- it says a "token" is missing on this line?
I'm trying to call a method from case 0, but it isn't working.
import java.util.Scanner;
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
private static void enterData()
{
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
You can't define method in another method.
Change your code to this:
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private static void enterData()
{
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
Scanner console = new Scanner(System.in);
System.out.println("Product name between 3 & 10 characters long: ");
String name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Try making a separate method and make those fields global. Something like this
import java.util.Scanner;
public class Interface {
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
private void run() {
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
do {
System.out
.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch (option) {
case 0:
enterData(console);
break;
case 1:
break;
case 2:
break;
case 9:
System.out.println("You chose to exit the program.");
break;
default:
System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private void enterData(Scanner console) {
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out
.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Interface is some kind of an abstract class definition keyword in java.
You can use a keyword to name your class with capitalized letters, but seriously, don't do this.
And you are not calling a method, you are implementing it in another method. You should go over writing and calling a method in java once again ;)