0% found this document useful (0 votes)
20 views

Arithmetic Operators

The document provides examples of Java programs to perform arithmetic operations and generate random numbers. The first program allows a user to input two integer values and prints the results of adding, subtracting, multiplying, and dividing those numbers. The second program generates a random number between 1 and 6 using the Random class.

Uploaded by

MahmoudMohammad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Arithmetic Operators

The document provides examples of Java programs to perform arithmetic operations and generate random numbers. The first program allows a user to input two integer values and prints the results of adding, subtracting, multiplying, and dividing those numbers. The second program generates a random number between 1 and 6 using the Random class.

Uploaded by

MahmoudMohammad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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);

You might also like