Advertisement
MrDoyle

Weekly Challenge #1: Basic Calculator

Oct 15th, 2020
2,022
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.33 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5.     public static void main(String[] args) {
  6.         System.out.println();
  7.         Scanner input = new Scanner(System.in);
  8.  
  9.         int num1 = 0;
  10.         int num2 = 0;
  11.  
  12.         System.out.print("Please input your first whole number: ");
  13.         if (input.hasNextInt()) {
  14.             num1 = input.nextInt();
  15.         } else {
  16.             System.out.println("\nThis is not a correct number, the program will now terminate");
  17.             System.exit(0);
  18.         }
  19.  
  20.         System.out.print("Please input your second whole number: ");
  21.         if (input.hasNextInt()) {
  22.             num2 = input.nextInt();
  23.         } else {
  24.             System.out.println("\nThis is not a correct number, the program will now terminate");
  25.             System.exit(0);
  26.         }
  27.  
  28.         System.out.println("\nFrom the menu below, enter the number of the operation you would like to perform:");
  29.         System.out.println("\t1) Add");
  30.         System.out.println("\t2) Subtract");
  31.         System.out.println("\t3) Multiply");
  32.         System.out.println("\t4) Divide (to the nearest whole number)");
  33.         System.out.print("> ");
  34.         int symbol = input.nextInt();
  35.  
  36.         System.out.println();
  37.  
  38.         if (symbol == 1) {
  39.             System.out.println("You have requested: " + num1 + " + " + num2);
  40.             System.out.println("And the answer is: " + (num1 + num2));
  41.         }else if (symbol == 2) {
  42.             System.out.println("You have requested: " + num1 + " - " + num2);
  43.             System.out.println("And the answer is: " + (num1 - num2));
  44.         }else if (symbol == 3) {
  45.             System.out.println("You have requested: " + num1 + " x " + num2);
  46.             System.out.println("And the answer is: " + (num1 * num2));
  47.         } else if (symbol == 4){
  48.             System.out.println("You have requested: " + num1 + " / " + num2);
  49.             if (num2 == 0) {
  50.                 System.out.println("You cannot divide by zero, the program will now terminate.");
  51.                 System.exit(0);
  52.             } else {
  53.                 System.out.println("And the answer is (rounded to the nearest whole number): " + (num1 / num2));
  54.             }
  55.  
  56.         }else {
  57.             System.out.println("Incorrect option selected, the program will now terminate");
  58.             System.exit(0);
  59.         }
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement