Advertisement
Glaciation96

Simple Calculator

Jan 20th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. package ProcessingFiles; //Does not catch any errors... May make a new version which utilises collections with try catch.
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class App {
  6.     public static void main(String[] args) {
  7.  
  8.         Scanner input = new Scanner(System.in);
  9.         System.out.println("Enter your first value: ");
  10.         String firstValue = input.nextLine();
  11.         System.out.println("Enter the second value: ");
  12.         String secondValue = input.nextLine();
  13.         System.out.println("Enter a chosen operator between +, -, /, *: ");
  14.         String op = input.nextLine();
  15.        
  16.         outPut(firstValue, secondValue, op);
  17.  
  18.     }
  19.     //Bad recursion practice. May lead to stack overflow.
  20.     public static void outPut(String val1, String val2, String op) {
  21.         double result = calc(val1, val2, op);
  22.  
  23.         if (result == -9999) {
  24.             System.out.println("You've entered an invalid operator");
  25.         }
  26.         else System.out.println("Result: " + result);
  27.        
  28.         Scanner input = new Scanner(System.in);
  29.         System.out.println("Would you like to go again? Enter yes or no: ");
  30.         String answer = input.nextLine();
  31.        
  32.         if(answer.equals("yes")) {
  33.             System.out.println("Enter your first value: ");
  34.             String firstValue = input.nextLine();
  35.             System.out.println("Enter the second value: ");
  36.             String secondValue = input.nextLine();
  37.             System.out.println("Enter a chosen operator between +, -, /, *: ");
  38.             String operator = input.nextLine();
  39.            
  40.             outPut(firstValue, secondValue, operator);
  41.         }
  42.         else System.out.println("Thank you.");
  43.     }
  44.  
  45.     public static double calc(String val1, String val2, String op) {
  46.         int firstValue = Integer.parseInt(val1);
  47.         int secondValue = Integer.parseInt(val2);
  48.         if (op.equals("+"))
  49.             return firstValue + secondValue;
  50.         else if (op.equals("-"))
  51.             return firstValue - secondValue;
  52.         else if (op.equals("*"))
  53.             return firstValue * secondValue;
  54.         else if (op.equals("/"))
  55.             return firstValue / secondValue;
  56.         else
  57.             return -9999;
  58.     }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement