﻿ Java exercises and solutions: Java arithmetic operators

# Java exercises and solutions: Java arithmetic operators

## Java arithmetic operators

### Exercise 1: Write Java program to allow the user to input two integer values and then the program prints the results of adding, subtracting, multiplying, and dividing among the two values.

See the example below:

Enter value a:30

Enter value b:10

The result of adding is 40.

The result of subtracting is 20;

The result of multiplying is 300.

The result of dividing is 3.

Solution:

import java.util.Scanner;
public class JavaExercises
{
public static void main(String[] args)
{
caculateValues();
}

static void caculateValues(){

int a,b;
int resulta,results,resultm;
float resultd;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a:");
a=sc.nextInt();
System.out.print("Enter b:");
b=sc.nextInt();
resulta=a+b;
results=a-b;
resultm=a*b;
resultd=(float)a/b;
System.out.println("The result of adding is "+resulta);
System.out.println("The result of subtracting is "+results);
System.out.println("The result of multiplying is "+resultm);
System.out.println("The result of dividing is "+resultd);

}

}

### Exercise 2: Write Java program to generate a random number between 1 to 6.

To generate a random number, you can use the Random class of java.util package. You may use the abs() method of Math class to make sure you can get only a positive number.

Solution:

import java.util.*;
public class JavaExercises
{
public static void main(String[] args)
{
caculateValues();
}

static void caculateValues(){

int a;
Random rn=new Random();
a=1+Math.abs(rn.nextInt()%6);
System.out.println("The result: "+a);

}

}