0

I have to create a calculator in Java. Everything works ok so far, except I can't quite figure out how to produce an error message when somebody enters a value that is not an integer when it asks for a number. I tried a "try, catch" statement but it still throws me an error in the IDE which is :

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)

here is the code for the rest of my program:

import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {

static int num1, num2;
static int memory;
static String operation;
static String menu = "\nChoose an operation:\n+ Add\n- Subtract\n* Multiply\n/ Divide\n^ Exponent\n~ Square Root\n Exit";
static boolean run = true;

public static void menu (String menu){
    System.out.println (menu);
};

public static void add (int num1, int num2) {
    System.out.println (num1 +num2);}

public static void subtract (int num1, int num2) {
    System.out.println (num1 - num2);           
};

public static void multiply (int num1, int num2) {
    System.out.println (num1 * num2);           
};

public static void divide (int num1, int num2) {
    if (num2 !=0) {
        System.out.println (num1/num2);}
    else{
        System.out.println ("Cannot divide by 0");
    };
};

public static void exp (int num1, int num2) {
    System.out.println (Math.pow(num1,num2));           
};

public static void sqrt (int num1) {
    System.out.println (Math.sqrt(num1));           
};

public static void main(String[] args) {
    Scanner scanner = new Scanner (System.in);

    do{
        menu(menu);
        operation = scanner.next();

        try {
        switch (operation) {
            case "+":
                System.out.println ("Enter first number:");
                num1 = scanner.nextInt();
                System.out.println ("Please enter a valid number");
                System.out.println ("Enter second number:");
                num2 = scanner.nextInt();
                add (num1,num2);    
                break;
            case "-":
                System.out.println ("Enter first number:");
                num1 = scanner.nextInt();
                System.out.println ("Enter second number:");
                num2 = scanner.nextInt();
                subtract (num1, num2);
                break;
            case "*":
                System.out.println ("Enter first number:");
                num1 = scanner.nextInt();   
                System.out.println ("Enter second number:");
                num2 = scanner.nextInt();
                multiply (num1, num2);
                break;
            case "/":
                System.out.println ("Enter first number:");
                num1 = scanner.nextInt();
                System.out.println ("Enter second number:");
                num2 = scanner.nextInt();
                divide (num1, num2);
                break;
            case "^":
                System.out.println ("Enter first number:");
                num1 = scanner.nextInt();
                System.out.println ("Enter exponent:");
                num2 = scanner.nextInt();
                exp (num1, num2);
                break;
            case "~":
                System.out.println ("Enter number:");
                num1 = scanner.nextInt();
                sqrt(num1);
                break;
            case "Exit":
                System.out.println("You have exited the calculator");
                System.exit(0);
                run = false;
                break;
            default:
                System.out.println("Invalid");
            }
        }catch (InputMismatchException e) {

        }
    }while(run == true);



    scanner.close();
        }

};

thanks!

ok update: i got the try catch to throw the error, but when i run it with the error, it runs the default case of the switch statement, and then runs again (so you see the menu twice) and I only need it to show up once

6
  • at com.catalyst.training.calculator.Calculator.main(Calculator.java:70). where is tje line 70? Commented Sep 24, 2015 at 15:23
  • So just to clarify where do you wana see the error message. Also don't use try catch for this instead make use of a while loop and keep on listening for an int. Commented Sep 24, 2015 at 15:47
  • When somebody is prompted to enter a number, and enters something other than an Int I want an error message and then have them prompted to enter a valid number Commented Sep 24, 2015 at 15:50
  • Dont use try catch for this. Instead use a while loop to keep on listening till you get a valid input. Commented Sep 24, 2015 at 15:52
  • If I use a do while loop can I still use the InputMismatchException in the while? Commented Sep 24, 2015 at 15:54

4 Answers 4

1
case "+":
                System.out.println ("Enter first number:");
                while(!scanner.hasNextInt())
                {
                    System.err.println("Enter valid int");
                    scanner.next();
                }

                num1 = scanner.nextInt();
                System.out.println ("Enter second number:");
                while(!scanner.hasNextInt())
                {
                    System.err.println("Enter valid int");
                    scanner.next();
                }

                num2 = scanner.nextInt();
                add(num1, num2);

                break;

Use something like this instead of a try catch block. This way it will listen till you get a valid num1. Similarly do for the other number too.

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry if this is a dumb question, but when I enter that into my case it won't run the rest of the code and prompt for a number
Yea you will have to modify your code a bit. Dont just copy paste lol
I have updatd the answer
1

Wrap the entire method with a try catch block. Your try/catch block is localized to a single area, it will only throw exceptions in that section.

Comments

0

You're using the Scanner.nextInt() method. When this sees an input that cannot be cast to an int, it will throw an InputMismatchException.

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()

You can verify that the next input is of type int by first checking "hasNextInt()".

1 Comment

right, so how do I throw an error message if it is not an int
0

It appears that your error is thrown when trying to multiply (case "*")... It is outside of a try/catch and therefore you will get this error. Either try/catch for each input or wrap the whole thing into a single swoop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.