Monday, May 11, 2009

Calculator in Java Console Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Calculator {


public static int validate(String input){//validate the user input value
try
{
int output = Integer.parseInt (input);//convert the string to integer
return output;
}
catch (Exception e){//if input value is not integer,return -1
System.out.println(e.getMessage());//print the exception message
return -1;
}
} //end validate function

/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub


BufferedReader br = new BufferedReader (new InputStreamReader (System.in));//read the input from console

while(true){

System.out.print ( "\nEnter the first number: " );

String input1 = br.readLine();//get input1

System.out.print ( "\nEnter the second number: " );

String input2 = br.readLine();//get input2

int num1 = validate(input1);//call the validate function and pass input1

int num2 = validate(input2);//call the validate function and pass input2

if(num1 == -1 || num2 == -1){//check the condition
System.out.println("You enter correct interger value...");
}
else{

System.out.println("\n1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Exit");

System.out.print( "Enter your choice : ");

int option = Integer.parseInt(br.readLine());//get the choice of the user

switch(option){//switch to the value of choice

case 1:

int addAnswer = num1 + num2;//add the user input value

System.out.println(num1+" + "+num2+" = "+addAnswer);

break;

case 2:

int subAnswer = num1 - num2;//Subtract the user input value

System.out.println(num1+" - "+num2+" = "+subAnswer);

break;

case 3:

int mulAnswer = num1 * num2;//Multiply the user input value

System.out.println(num1+" * "+num2+" = "+mulAnswer);

break;

case 4:


if(num2 != 0){

double divAnswer = (double)num1 / (double)num2;//Divide the user input value and assign to double

System.out.println(num1+" / "+num2+" = "+divAnswer);

}else{

System.out.println ("Division by zero is not allowed!");
}

break;

case 5:

System.exit(0);//exit the program

default:

System.out.println("Enter your correct choice...");

}//end switch statement
}

}//end while loop

}//end main method
}

Post a Comment

  © Blogger templates Newspaper III by Ourblogtemplates.com 2008

Back to TOP