Created
February 19, 2013 02:49
-
-
Save mseeks/4982688 to your computer and use it in GitHub Desktop.
A simple calculator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package calculator; | |
import java.util.Scanner; | |
/** | |
* Calculator | |
* A class that offers simple calculator functionality. | |
* | |
* @author Matthew Sullivan | |
*/ | |
public class Calculator { | |
/** | |
* @param args the argument strings | |
*/ | |
public static void main(String[] args) { | |
double total = 0.00; | |
double lastNumber = 0.00; | |
Scanner console = new Scanner(System.in); // my input | |
/** | |
* Be a polite calculator. | |
*/ | |
System.out.println("This is a simple calculator. Enter a number followed by the operator on a new line."); | |
try { | |
lastNumber = Integer.parseInt(console.next()); // get the first line | |
} catch(Exception e) { | |
lastNumber = Double.parseDouble(console.next()); // again, but if it's a double | |
} | |
while(!console.nextLine().equals("stop")) { // allow an exit like a gentleman | |
String line = console.next(); // assign the line variable | |
switch(line) { | |
case "+": | |
total += lastNumber; // add to the total | |
break; | |
case "-": | |
total -= lastNumber; // or subtract | |
break; | |
case "*": | |
total *= lastNumber; // or multiply | |
break; | |
case "/": | |
if(lastNumber != 0) { | |
total /= lastNumber; // or divide | |
} else { | |
System.out.println("If you divide by zero the universe implodes, so how about not."); | |
} | |
break; | |
case "=": | |
System.out.println(total); // tell us the grand total! | |
break; | |
default: | |
try { | |
lastNumber = Integer.parseInt(line); // look for an int to assign | |
} catch(Exception e) { | |
lastNumber = Double.parseDouble(line); // look for a double | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment