Tuesday, April 2, 2013

Simple calculation program with Java

In the SimpleCalculation program, you learn how to perform simple calculations in Java.
You will use the Scanner object to read number from keyboard.

SimpleCalculation source code:

1. import java.util.Scanner;
2. class SimpleCalculation{
3.   public static void main(String[] args){
4.        int val1,val2, resul;
5.        Scanner sc=new Scanner(System.in);
6.        System.out.println("Enter first value:");
7.        val1=sc.nextInt();
8.        System.out.println("Enter second value:");
9.        val2=sc.nextInt();
10.      resul=val1+val2;
11.      System.out.println("Result:"+resul);
12.   }
13.}

Program Output
Enter first value:12
Enter second value:23
Result:35

Code Explanation:

1. Tell the Java compiler to include the Scanner class in the program. The Scanner class has nextInt() method
that allows you to read integer value from keyboard.
2. Open the SimpleCaculation class block.
3. Open the main method that defines the starting point of the program.
4. Declare local variables val1, val2, and resul that are used to store numbers and result of sum operation.
5. Create Scanner object so that you can use the nextInt() method to get user input.
6. Tell the user to input the first number.
7. Read the first number and place it in the val1 variable.
8. Tell the user to input the second number.
9. Read the second number and place it in the val2 variable.
10. Add val1 and val2 together. The result will be assigned to the resul variable.
11. Display the output
12. Close main method
13. Close SimpleCalculation class

No comments:

Post a Comment