Java calculator

By | 11/11/2014

This program asks for two numbers and the mathematical operator to use on them.

Calculator.java:

import java.util.Scanner;

public class Calculator {
 public void run()
 {
  Scanner numberReader=new Scanner(System.in);
  Scanner textReader=new Scanner(System.in);
		
  double number1, number2;
  String operator, result, rounding1, rounding2;
		
  System.out.print("Enter first number: ");
  number1=numberReader.nextDouble();
		
  System.out.print("Enter second number: ");
  number2=numberReader.nextDouble();
		
  System.out.print("Operation: ");
  operator=textReader.nextLine();
		
  numberReader.close();
  textReader.close();

  if(operator.equals("+"))
  {
   result=String.format("%.2f", (number1+number2));
   rounding1=String.format("%.2f", (number1));//round to second decimal
   rounding2=String.format("%.2f", (number2));
   System.out.println(rounding1+" + "+rounding2+" = "+result);
  }
  else if(operator.equals("-"))
  {
   result=String.format("%.2f", (number1-number2));
   rounding1=String.format("%.2f", (number1));
   rounding2=String.format("%.2f", (number2));
   System.out.println(rounding1+" - "+rounding2+" = "+result);
  }
  else if(operator.equals("*"))
  {
   result=String.format("%.2f", (number1*number2));
   rounding1=String.format("%.2f", (number1));
   rounding2=String.format("%.2f", (number2));
   System.out.println(rounding1+" * "+rounding2+" = "+result);
  }
  else if(operator.equals("/"))
  {
   result=String.format("%.2f", (number1/number2));
   rounding1=String.format("%.2f", (number1));
   rounding2=String.format("%.2f", (number2));
   System.out.println(rounding1+" / "+rounding2+" = "+result);
  }
  else if(operator.equals("%"))//remainder
  {
   number1=(int)number1*1;//save value as int
   number2=(int)number2*1;
			
   System.out.println((int)number1+" % "+(int)number2+" = "+(int)number1%(int)number2);
  }
  else
  {
   System.out.println("Wrong value given");
  }
 }
 public static void main(String[] args)
 {
  Calculator program = new Calculator();
  program.run();
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *