Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package calculator;
- import java.util.Scanner;
- public class Calculator {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- int x, y, ans, ans2;
- char op, res;
- // Loops the program in case the user wishes to calculate multiple problems
- do
- {
- ans = 1;
- ans2 = 1;
- // Prints a list of supported operations
- System.out.println("-------------------------------");
- System.out.println("List of operations:\n");
- System.out.println("Addition: +\nSubtraction: -\nMultiplication: *\nDivision = /\nModulus: %\nFactorial: !");
- System.out.println("-------------------------------\n");
- // User input
- System.out.print("Enter first value: ");
- x = input.nextInt();
- System.out.print("Enter second value: ");
- y = input.nextInt();
- System.out.print("Enter operation: ");
- op = input.next().charAt(0);
- // Checks to see if an inputted operation is incorrect
- while((op != '+') && (op != '-') && (op != '*') && (op != '/') && (op != '%') && (op != '!'))
- {
- System.out.print("Unrecognized operation. Please re-enter: ");
- op = input.next().charAt(0);
- }
- // Checks to see if the user is trying to divide by zero
- while((op == '/') && (y == 0))
- {
- System.out.print("Cannot divide by 0. Please re-input second value: ");
- y = input.nextInt();
- }
- // Addition
- if(op == '+')
- {
- ans = x + y;
- }
- // Subtraction
- else if(op == '-')
- {
- ans = x - y;
- }
- // Multiplication
- else if(op == '*')
- {
- ans = x * y;
- }
- // Division
- else if(op == '/')
- {
- ans = x / y;
- }
- // Modulus Division
- else if(op == '%')
- {
- ans = x % y;
- }
- // Factorial
- else
- {
- for(int i = 1; i <= x; i++)
- {
- ans = ans * i;
- }
- for(int w = 1; w <= y; w++)
- {
- ans2 = ans2 * w;
- }
- }
- // Prints answer for factorial
- if(op == '!')
- {
- System.out.println("The factorial of " + x + " is " + ans + ".");
- System.out.println("The factorial of " + y + " is " + ans2 + ".");
- }
- // Prints answer if not a factorial
- else
- {
- System.out.println("The answer is " + ans + ".");
- }
- // Asks the user if they would like to reset the calculator and input another problem
- System.out.print("Would you like to reset? (y/n): ");
- res = input.next().charAt(0);
- // Checks for caps sensitive answers
- while((res == 'Y') || (res == 'N'))
- {
- System.out.print("This program is case sensitive. Please re-input in lowercase: ");
- res = input.next().charAt(0);
- }
- // Checks for responses other than yes or no
- while((res != 'y') && (res != 'n'))
- {
- System.out.print("Unrecognized response. Please re-enter: ");
- res = input.next().charAt(0);
- }
- }while(res == 'y');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement