1

I am new to Java and programming in general. I've encountered not exactly a problem, but more like a wall of my ignorance. On my QA Automation courses I was asked to write a simple calculator program in Java, I kept it very basic - you needed to launch the program over again every time you preformed a calculation. I learned about while loops and it seemed the while loop was a good solution to keep the program running. But now I am at another extreme - the loop is infinite. My question is: is there any simple way to exit the program without re-writing the code and the way I've structured my calculator? I don't know how to do it but it would be nice if program would end when user presses [Esc] or prints "Exit". Is there a simple way that I (beginner) would understand and could implement?

import java.io.IOException;
import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        int first, second, answer;
        String operator;

        Scanner s = new Scanner(System.in);

        try {
            while (true) {
                log("Please enter a math equation using +, -, * or /");
                first = s.nextInt(); //User enters first number
                operator = s.next(); //User enters operator
                second = s.nextInt(); //User enters second number

                if (operator.contains("+")) {
                    answer = first + second;
                    log("" + answer);
                }

                if (operator.contains("-")) {
                    answer = first - second;
                    log("" + answer);
                }

                if (operator.contains("*")) {
                    answer = first * second;
                    log("" + answer);
                }

                if (operator.contains("/")) {
                    if (second == 0) {
                        log("You can't divide by 0");
                    } else {
                        answer = first / second;
                        log("" + answer);
                    }
                }
            }
        } catch (java.util.InputMismatchException error) {
            log("Incorrect input");
        }
    }

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

Thank you, if you can help me! P.S. I don't know if it is a correct way to handle exceptions or a very ugly one. I'd appreciate if you could comment on that too.

hickstead
  • 11
  • 1
  • also...why not use a switch statement instead of all the if statements? – SuncoastOwner Dec 16 '14 at 18:11
  • @SuncoastOwner switch only works with `byte`, `char`, `short` or `int` types. – Marv Dec 16 '14 at 18:15
  • Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings). from http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html – SuncoastOwner Dec 16 '14 at 18:23
  • I stand corrected, but still, no boolean, which is what `String`s `contains()` method returns. – Marv Dec 16 '14 at 18:30

3 Answers3

8

Yes, use break:

if(endingCondition)
    break;

This will break out of the innermost loop.

Marv
  • 3,517
  • 2
  • 22
  • 47
  • How do I program in ending condition [Esc]? User would not be able to enter word "Exit", because I use s.nextInt() and if I change that to s.next() I would need to check the input (whether it's an integer or not) in all of my ifs. – hickstead Dec 16 '14 at 18:21
2

In order to follow your example and not deviate from it focusing on other code improvements, you should have to change the way you read the parameters, because the way you do it now, you could never read the exit word to get out. In order to do this you can use the following approach:

This will add a new string parameter to read the exit or the first operand (in string format). Then, it will transform it into an int:

int first, second, answer = 0;
    String operator, firstParam = "";

    Scanner s = new Scanner(System.in);

    try {
        while (true) {
            System.out.println("Please enter a math equation using +, -, * or /, or exit if you want to stop the program");

            firstParam = s.next(); //User enters first number or exit
            // This first param is read as a String so that we are able to read the word exit
            if(firstParam.equals("exit"))
                break;
            first = Integer.valueOf(firstParam); // This will transform the first parameter to integer, because if it reaches this point, firstParam won't be "exit"
            //[... Rest of your program...]
        }
    } catch (java.util.InputMismatchException error) { ... }
0

TIPS FOR ERROR HANDLING

1: You don't have to specify the complete reference of the InputMismatchException while in catch block because you have already imported the java.util package

catch (InputMismatchException e)
{
    //handle exception here
}

2: In case you are unsure about the type of Exception that can thrown, just catch the object of class Exception. Since Exception is the super class for all the Exceptions, it can handle all exceptions.. This would work perfectly for beginners.

catch (Exception e)
{
 //handle exception
}

3: You can handle multiple exceptions for the same try block, each catch handling a particular type of exception. Give it a try.

FOR EXITING THE LOOP

if (s1.contains("EXIT"))
break;

Here s1 is the string, and if the string contains the word EXIT (ALL CAPS ONLY), the loop will terminate.

Atul Goel
  • 18
  • 5