/**********************************************
Description: This is an interactive program using
menu and calculator.
***********************************************/
import java.util.Scanner;
public class Interactive {
public static void main(String args[]) {
// vars for the repeat loop
boolean repeat = true;
char ans;
// var to hold our integer input
int n;
// var to hold a float
float j;
// we need to declare a new scanner object, hence the new keyword
Scanner sc = new Scanner(System.in);
/*
* When using a while loop, we need to define some kind of conditional
* to check against, otherwise it would (or should) just evaluate to true
* which we don't want because it would, in theory, run forever.
*/
while (repeat == true){
// print out a menu for the user
System.out.println( "This is a simple Calculator" );
System.out.println( "\n********Menu********" );
System.out.println( "1: Add" );
System.out.println( "2: Subtract" );
System.out.println( "3: Multiply" );
System.out.println( "4: Divide" );
System.out.println( "********************\n" );
System.out.println("Choice? >> ");
// get the input from the user
n = sc.nextInt();
if ( n == 1 ) {
System.out.print( "Please input two integers to add: " );
int n1 = sc.nextInt();
int n2 = sc.nextInt();
System.out.println( n1 + " + " + n2 + " = " + (n1+n2) );
} else if ( n == 2 ) {
System.out.println( "Please input two integers to subtract: " );
int n1 = sc.nextInt();
int n2 = sc.nextInt();
System.out.println( n1 + " - " + n2 + " = " + (n1-n2) );
} else if ( n == 3 ) {
System.out.println( "Please input two integers to multiply: " );
int n1 = sc.nextInt();
int n2 = sc.nextInt();
System.out.println( n1 + " * " + n2 + " = " + (n1*n2) );
} else if (n == 4 ) {
System.out.println( "Please input two integers to divide: ");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
while (n2 == 0) {
System.out.println("You cannot divide by zero!\n");
System.out.println("Please re-enter your two integers to divide: ");
n1 = sc.nextInt();
n2 = sc.nextInt();
}
float tmpn1 = new Float(n1);
float tmpn2 = new Float(n2);
System.out.println( n1 + " / " + n2 + " = " + (tmpn1/tmpn2) );
}
do {
System.out.println("Would you like to try again? ");
ans = sc.next().charAt(0);
} while ((ans != 'Y') && (ans != 'y') && (ans != 'N') && (ans != 'n'));
if (ans == 'N' || ans == 'n') {
repeat = false;
System.out.println("Thanks for trying the Interactive Calculator!\n");
System.exit(0);
}
}
}
}