Java Beginner: Lesson 3

Arithmetical operations


In this lesson we will se the arithmetical operations by creating a simple calculator. we will use the primitive data type double in order to have precision during division.


In order to be abble to create the calculator we have to get input from user. We get get output from user for double variables through following line:
scanner.nextDouble()


Where scanner is an instance of Scanner class.

For the operator we will use a String variable, but we can use char as well. In order to be able to retriev a string variable from user we writte the following line:
scanner.next()

After retrieving the 2 double variables and the operation sign we have to check the type of the operation through if condition statment. Also we can check for illegal operations as well, for example for division with 0 which I have implemented in the example.


Bellow you will see the complete code of the example.



Example code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package helloworld;

import java.util.Scanner;

/**
*
* @author ahoxha
*/
public class HelloWorld {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner scanner = new Scanner(System.in);
double nr1=0;
double nr2=0;
String operation;
double result =0;
System.out.println("Give the first number: ");
nr1= scanner.nextDouble();
System.out.println("Give the operation: ");
operation = scanner.next();
System.out.println("Give the second number: ");
nr2= scanner.nextDouble();
if(operation.equalsIgnoreCase("+")){
result = nr1+nr2;
}else if(operation.equalsIgnoreCase("-")){
result = nr1-nr2;
}else if(operation.equalsIgnoreCase("*")){
result = nr1*nr2;
}else if(operation.equalsIgnoreCase("/")){
if(nr2!=0){
result = nr1/nr2;
}else{
System.out.println("Can not devide by 0\n");
return;
}
}

System.out.println("The result of nr1 and nr2 is "+ result);
}

}



Execution example 1:

Figure 1: Multiplication


Execution example 2:

Figure 2: Illegal operation

(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game