0% found this document useful (0 votes)
28 views52 pages

JAVA File

Java1

Uploaded by

tailortrendy366
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views52 pages

JAVA File

Java1

Uploaded by

tailortrendy366
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Problem solving using Java – CSE1006

[L-T-P-C: 1-0-4-3]

MODULE – 1
Basic Concepts of Programming and Java

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 1


• Course Handout Discussion
• Program Integration and Course integration
• Programming and Types of Programming Languages
• History & Introduction to Java

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 2


Problem
• A problem is a puzzle that requires
logical thought or mathematics to Follow
solve up on
• A puzzle could be a set of questions Implement Solution
on a scenario which consists of the Solution
description of reality and set of Decide on
constraints about the scenario. a Solution
Consider
Problem
Solutions
Establish
Criteria
Problem Solving
Analyze the
Problem
Define the Problem

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 3


Problem Solving Approach ALGORITHM

PROBLEM LOGIC PROGRAM

• What is Program? FLOWCHART

An approach to find solution to the Problem


• What is Programming ?
Solving Problem in Engineering approach / Systematic Procedure.
• What is Programming Language ?
Tool to solve problem

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 4


How to Develop a Program
Step1: Analyze the problem to identify inputs, outputs and processing requirements
Step2: Identify various processing steps needed to solve the problem and represent them in a
particular way (algorithm, flow charts, etc..)
Step3: Refine step 2 in a way that all the processing steps are detailed enough such that every
processing step is equivalent to one instruction of the programming language.
Step4: Add syntax of the programming language to the above representation and it becomes the
program.
Step5: Type the program and Compile it after removing all syntax related errors.
Step6: Run the program and check it with different types of input to verify its correctness.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 5


Algorithm
Some characteristics of an algorithm are as
• The algorithm is part of the blueprint or plan for the
follows:
computer program, an algorithm is:
1. Each step of an algorithm must be precisely
“An effective procedure for solving a class of problems in
defined.
a finite number of steps.”
2. An algorithm must contain blocks that will
• An algorithm is defined as the sequence of instructions
help to solve problems more efficiently and
written in simple English that are required to get the
logically.
desired results. It helps to develop the fundamental
logic of a problem that leads to a solution. 3. It should accept a set of inputs and produce
a defined output.
• Every algorithm should have the following 5
characteristic feature: 4. It must be terminated after a finite number
of steps.
1. Input 4. Effectiveness
2. Output 5. Termination 5. It should be independent from a computer
3. Definiteness programming language.
6. It should develop a platform for writing
programs.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 6


Algorithm Examples ALGORITHM
1) Start
2) Grind the coffee beans
3) Add water and milk in a coffee making vessel
4) Ignite the stove and place the vessel on top of it
Prepare Coffee 5) Let the mixture to boil and add the coffee powder to the mixture
6) Filter the mixture
7) If sugar is not needed then, go to step 9
Else, Add sugar to mixture
8) If cream is not needed then, go to step 9
Else add cream to the mixture
9) Serve the coffee in a cup
10) Stop

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 7


Algorithm Examples ALGORITHM
1) Start
To Find Largest of Three Numbers 2) Read 3 numbers: num1, num2, num3
3) if num1 > num2 then go to step 5
4) if num2 > num3 then
Activity
print num2 is largest
Q1. Accept the length of two different line segments
and check whether they are equal or unequal. Display else
the message accordingly. print num3 is largest
Q2. Accept three integer numbers and check whether goto step 6
they are 'Pythagorean Triplets' or not. Display the 5) if num1 > num3 then
message accordingly.
print num1 is largest
(Hint: Use Pythagoras Formula for a Right-angled
Triangle: r2=p2+q2 ) else
print num3 is largest
6) end.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 8


Flowchart Basic Flowchart Shapes and Definitions
Split Manual
or
• Rounded box: use it to represent an event Start / End
Merge Input
which occurs automatically. The start or end of a Upright indicates a
Prompt for
information,
• Rectangle or box: use it to represent an workflow. process split, inverted
manually entered
indicates a merge of
into a system.
processes.
event which is controlled within the
process. Typically this will be a step or
action which is taken. Decision Connector
Project / Task
• Diamond: use it to represent a decision Used to connect one
point in the process. Process or action. Decision point in a part of a flowchart to
process or workflow. another.
• Circle: use it to represent a point at which
the flowchart connects with another Input / Output Off Page
process. Document
Connector
Data: Inputs to, and outputs
from, a process.
Document or Connector used to
report. connect one page of a
flowchart to another.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 9


Flowchart Example

Coffee Grinder
Start Grind Beans Task

Inputs
Merge
Read Add Filter
Instructions

Coffee Pot
Add Coffee Brew
Brewing Coffee
Document
Add Water
Inputs

Decision Yes
Cream Sugar Pour
Yes
Coffee Mug

No Decision Manual Input


Finish Drink
No
Task

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 10


Flowchart Example
Flowchart to find the largest of three
numbers A,B, and C:

Activity
Q1. Accept the length of two different line segments
and check whether they are equal or unequal. Display NO
the message accordingly.
Q2. Accept three numbers and check whether they are
'Pythagorean Triplets' or not. Display the message
accordingly.
(Hint: Use Pythagoras Formula for a Right-angled
Triangle r2=p2+q2 )

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 11


Computer Programming Languages
• A programming language is an artificial language that can be used to control the behavior of a
machine, particularly a computer
• Programming languages, like human languages, are defined through the use of syntactic and
semantic rules, to determine structure and meaning respectively.
• Programming languages are used to facilitate communication about the task of organizing and
manipulating information, and to express algorithms precisely.
• Over the last few decades, computer programmers have been writing code. New technologies
continue to emerge, develop, and mature at a rapid pace. Now there are more than 2,500
documented programming languages!

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 12


Types of Programming Languages
Programming Languages

Low Level Languages High Level Languages

Object Oriented
Machine Assembly Languages
Language Language
4th Generation
1st Generation 2nd Generation

Imperative Functional Declarative


Languages Languages Languages

3rd Generation

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 13


Introduction To Java

James Arthur Gosling often referred to as Dr. Java, OC is a Canadian computer scientist,
best known as the founder and lead designer behind the Java programming language.

Java is a famous and widely used object-oriented programming language. It was


developed by Sun Microsystems in 1995. Later in 2009, Oracle Corp. acquired Java.

• Initially Java called as OAK, Later it is termed as Java ( a name given to coffee bean)
• Java is modelled after C++, Java language was designed to be small, simple, and
portable across platforms and operating systems, both at the source and at the binary
level.
• Java also provides for portable programming with AWT.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 14


Introduction To Java Flavor's Of Java
❑ JSE
• Java Standard Edition formerly known as J2SE.
• This forms the core part of Java language.
❑ JEE
• Java Enterprise Edition formerly known as J2EE.
• These are the set of packages that are used to develop distributed enterprise-scale
applications.
• These applications are deployed on JEE application servers.
❑ JME
• Java Micro Edition formerly known as J2ME.
• These are the set of packages used to develop application for mobile devices and
embedded systems.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 15


Activity Algorithms and Flowchart

Q1: Accept the length of two different line segments and check whether they are equal or unequal. Display
the message accordingly.
Q2: Accept three numbers and check whether they are 'Pythagorean Triplets' or not. Display the message
accordingly. (Hint: Use Pythagoras Formula for a Right-angled Triangle: H2 = P2+B2)

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 16


L2- Content
• Installation and Demonstration to run a program
• Fundamentals
• Java Programming - Editing, Compiling and Running a ‘Java’ Program
• Integrated Development Environments
• Basic Input / Output Stream
• Practical exercise

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 17


JDK Installation – Java Development Kit
How To Install JDK on Windows
• Download JDK@ https://www.oracle.com/in/java/technologies/javase-downloads.html
• Install JDK

Click Here

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 18


JDK Installation – Java Development Kit
Environment Setup
• Include JDK's "bin" Directory in
the PATH
Right click mycomputer->Properties
-->Advance Setting
->Click Environment Variable
-> Under System variables
->Select Path and click Edit
->Under Edit menu Click New
->Paste the path of “bin”->ok ->ok

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 19


JDK Installation - Confirmation

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 20


After JDK Installation JVM, JRE & JDK – After Installation
❑ JVM
stands for Java Virtual Machine which provides the runtime environment for Java
bytecodes to be executed.

❑ JRE (Java Runtime Environment)


includes the sets of files required by JVM during runtime.

❑ JDK (Java Development Kit)


consists of JRE along with the development tools required to write and execute a
program.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 21


After JDK Installation JVM, JRE & JDK – After Installation

SOURCE CODE Compiler BYTE CODE

OUTPUT Interpreter

JVM JVM + JRE MACHINE

OPERATING SYSTEM Interpreter


Memory
Management
HARDWARE JIT/Compiler MACHINE CODE

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 22


After JDK Installation JVM, JRE & JDK – After Installation
• To execute Java program, JRE must be installed in the system
• JRE or Java Runtime environment contains
o Java Virtual Machine
o Standard class libraries (APIs)
o Java Plug-in
o Java Webstart
• JRE gets installed automatically when JDK is installed. JRE can be installed
independent of JDK as well. This will mean that Java programs can be executed in that
system.
SOURCE CODE BYTE CODE JVM
Compile Interpreter Machine Code MACHINE
(filename.java) (filename.class)

Platform Independent Platform Dependent

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 23


Fundamentals Java Program Structure

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 24


Java Programming Editing, Compiling and Running a ‘Java’ Program
Fundamentals
Step What is done Command Comments

1 Editing C:>notepad Presidency.java

class Presidency { //Note: class name is same as the filename


public static void main(String[] args) {
System.out.println(“Welcome to Presidency University");
}
}
The class file “Presidency.class” is
2 Compiling C:> javac Presidency.java generated

3 Executing C:> java Presidency Output: Welcome to Presidency


University

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 25


Java Programming public static void main(String[] args)

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 26


Basic I / O System
Source Dot(.) Destination
in out

System.in System.out
Input Stream Output Stream
101010001 Program 101010001

• Scanner class ( java.util.Scanner )


• Command Line Arguments ( String args[ ] )

• System.out.print(“ ”)
• System.out.println(“ ”)
• And so on…

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 27


Development Environments Demonstration of Sample program in Eclipse

• There are many programs that support the development of Java software, including:
- Sun Java Development Kit (JDK) - Borland JBuilder
- Sun NetBeans - MetroWerks CodeWarrior
- IBM Eclipse - BlueJ
- jGRASP - Visual Studio Code (VS Code)
• Though the details of these environments differ, the basic compilation and execution
process is essentially the same.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 28


• Command Line Arguments
• Data Types
• Identifiers
• Variables
• Literals or Constants

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 29


Java Programming Command Line Arguments
Java Command Arguments separated by space are sent to main method

Java Demo word0 word1 . . . .

public class Demo {


public static void main ( String args[ ] ) {
for(int i = 0; i<args.length; i++) { args[0] = “word0”
System.out.println("args[" + i + "]: " + args[i]); args[1] = “word1”
} }}
and so on

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 30


Data Types Data Types

Primitive Non Primitive


Numeric
Strings
Integer Floating Point
Arrays
byte short
float double
int long
User Defined
Classes
Non-Numeric

Character Boolean

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 31


Data Types

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 32


Identifiers
Rules for Identifiers:
1. We can get the valid identifiers from the above code snippet. Now we will see the thumb rules as
described following.
Java identifier must start with a alphabetic (a-z or A-Z) or Dollar symbol ($) or underscore (_).
2. Identifiers should not start with a digit (0-9). If we use the digit at starting of it then will get compile
time error.
3. Digits can be used after the first legal character.
4. No limit for the identifiers length in java but size should be less which is better to
maintain understandable identifiers
5. In Java, all identifiers are case sensitive. Java treats itemsCount and ItemsCount as different identifiers.
6. Can not be used java inbuilt keywords as identifiers. E.g. static --> is a not valid.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 33


Variables public class Person {
private String name; //attribute (instance variable)
Syntax: Datatype Identifier;
public void method1(String yourName) //parameter
Or
Datatype Identifer=value; {
String myName; // local variable
Forms of Variables ……… } }

• Instance Variables public class Demo{

public static void main(String [] args) {


• Local Variables
Person obj=new Person(); // class variable
• Class variables ………

}}
Literals or Constants
• There are 5 types of Literals or constants in Java language.
1. Integer Literals (Decimal, Octal, Hexadecimal and Binary
Literals)
2. Floating Point Literals
3. Boolean Literals
4. Character Literals
5. String Literals
• JDK 7 introduced two new features namely Binary
Literals and Underscores in number literals.
• Underscore should not be at the beginning or end. Similarly not
before or after a DOT or Decimal Point in floating point or double
numbers. Underscore symbols are removed before processing.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 35


L4 - Content
• Operators
• Assignments and Expressions
• Control Statements
• Activity

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 36


& | ^ ~ << >> >>>
Operators
Bitwise Operators

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 37


Operators Shift operators in Java

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 38


Assignments & Expressions Evaluation of Expressions and Type Casting
Widening or Automatic Type Conversion
Syntax: variable = expression; • Widening conversion takes place when two data types are
automatically converted. This happens when:
• The two data types are compatible.
Example: • When we assign a value of a smaller data type to a bigger data type.

Score = (10 * Points )+10; Byte short int long float double
Ex: int i=100; float=i;
Variable Expression Narrowing or Explicit Conversion
• If we want to assign a value of a larger data type to a smaller data
type we perform explicit type casting or narrowing.
• This is useful for incompatible data types where automatic
conversion cannot be done.
Is Assigned to • Here, the target type specifies the desired type to convert the
specified value to.
double float long int short byte
Ex: int i=100; byte b=i;

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 39


Control Statements Control Flow
Statements

Looping Branching
Statements Statements

for Simple-if

if -else
for - each

Nested- if –else
while
if –else-ladder

do - while
switch - case

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 40


Activity

Q1. Accept the length of two different line segments and check whether they are equal or unequal. Display
the message accordingly. (Hint: Use scanner class to take the input)

Q2. Accept three numbers and check whether they are 'Pythagorean Triplets' or not. Display the message
accordingly. (Hint: Use command line arguments and Pythagoras Formula for a Right-angled Triangle: h =
p2+b2)

Q3. Define a class called Command Line, develop a program in Java that accepts two floats and integers as its
command line arguments and perform addition and multiplication on integer inputs, subtraction and division
on float inputs and display the result using function/method.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 41


1

(Established under the Presidency University Act, 2013 of the Karnataka Act 41 of 2013)

Course Code : CSE1006 Course Title : Problem solving using java

Labsheet -1

1. A teacher in a school wants to calculate the average marks of a student in three subjects
to assess their overall performance. Help the teacher to develop a program that accepts
the marks of three subjects and calculates the average.
Java Code:

// Close the scanner, it requires when VS code compiler is used


scanner.close();

}
}
===================
2

Naming conventions in java:


PascalCase (Upper Camel Case)
In PascalCase, each word in the identifier is capitalized, including the first one.
PascalCase is primarily used for naming classes and interfaces in Java.
Example include Factorial, EmployeeTax and SumOfTwoNumbers
camelCase (Lower Camel Case)
camelCase is similar to PascalCase, but the fi

rst letter of the first word is in lowercase. It’s commonly used for naming variables
and methods.

Examples include customerService, marksInMaths, studentProfile and


2.employeeTax()
Presidency University collect student information during enrollment for the even
semester. The program uses the Scanner class to take input (such as name, age, marks
and gender) from the student and displays the information entered. Help the Presidency
University by writing an application in java to perform the same. (Hint: Use Scanner
Class to take the Input from the User)

Java Code:
3
4

========================

// above program can also be written by assigning values to the variables as below

public static void main(String[] args) {

// Assigning student details using all data types

String studentName = "Zoya Hussain"; // String for textual data

int studentID = 123; // int for unique student ID

byte age = 20; // byte for age (small range)

char grade = 'A'; // char for grade

float percentage = 89.75f; // float for percentage

double attendance = 92.345; // double for attendance (higher precision)

long contactNumber = 9876543210L; // long for contact number

short yearOfEnrollment = 2023; // short for enrollment year

boolean isEnrolled = true; // boolean to check enrollment status

=======================
5

3. Demo program on Command line arguments.


1) Type the below program with file name Cities.java and compile using the
compile using the command: javac Cities.java
2) Run this program using below command:
java Cities Bengaluru Hyderabad Chennai Vijayawada Mumbai

class Cities {
public static void main(String args[]) {
System.out.println("command line arguments are");
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
----------------------------------------

Convert string to primitive int.


There are some situations where we need to convert a number represented as a string
into an integer type in Java. It is normally used when we want to perform
mathematical operations on the string which contains a number.

To convert string to an int, we use Integer.parseInt() method from the Integer class.
The parseInt() of Integer class is the static method, its syntax or general signature is
as below:

public static int parseInt(String s)

This method accepts a string containing the int representation to be parsed. It returns
the integer value.

Note : The parseInt() method throws an exception named NumberFormatException


if the string does not contain a parsable integer.
Exception handling will be discussed in Module:4.

(Note: Similarly students has to learn parseFloat(), parseDouble() methods from


Reference Materials given in Course Plan)
6

// practice program
public class StringToInt{
public static void main(String[] args)
{
// Create a string literal
String text = "123";
// Convert string into int using Integer.parseInt() method.
int num = Integer.parseInt(text);
// Print value of num.
System.out.println(num);
}
}
===================
4. Demo program on Command line arguments.
a. Type the below program with file name Temperature.java and compile using
the compile using the command: javac Temperature.java
b. Run this program using below command: java Temperature 32.1 32.2
import java.util.*;
class Temperature{
public static void main(String[] args) {
float t1 = Float.parseFloat(args[0]);
float t2 = Float.parseFloat(args[1]);
float avg=(t1+t2)/2;
System.out.println("average temperature is " + avg);
}
}
===================
5. Vishal is redesigning her living room and plans to install an air conditioner. The air
conditioner manual specifies that it is suitable for rooms up to 80 cubic meters in
volume. Vishal's living room has the following dimensions:
Length: 6.1 meters
Breadth or Width: 4.0 meters
Height: 3,1 meters
7

Tasks:
a) Calculate the volume of Amara’s living room.
b) Determine whether the air conditioner is suitable for the room.
c) If the room’s height is increased to 4 meters, calculate the new volume and reassess
if the air conditioner is still suitable.

// a) Calculate the volume of Vishal’s living room.


import java.util.Scanner;
public class RoomVolume {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner sc = new Scanner(System.in);
double length,breadth,height;
// Prompt the user to enter the dimensions of the room
System.out.print("Enter the length, breadth and height of the
room in meters");
length = sc.nextDouble();
breadth = sc.nextDouble();
height = sc.nextDouble();
// Calculate the volume
double volume = length * breadth * height;
// Display the volume
System.out.println("The volume of the room is: " + volume+ ”cubic
meters ” );
// Close the scanner
sc.close();
}
}

Activity1 : Students has to develop logic for tasks b & c using java application.
=======================

6. Raghu is an employee at HDFC Bank. He wants to develop a Java


application to check if a user has sufficient balance to perform a
withdrawal.

import java.util.Scanner;

public class BalanceCheck {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

double accountBalance = 15000.00; // Example account balance


8

System.out.println("Enter the withdrawal amount: ");


double withdrawalAmount = sc.nextDouble();

if (withdrawalAmount <= accountBalance) {


accountBalance -= withdrawalAmount;
System.out.println("Withdrawal successful! New balance: "
+ accountBalance);
} else {
System.out.println("Insufficient funds. Please check your
balance.");
}
sc.close();
}
}
========================

Activity 2: Student has to refer Student Hand Book available in University website and
develop code for the below scenario.

Develop an application to determine whether a student is eligible for promotion from the
first year to the second year.

========================

7. A power distribution company charges its customers based on the number of units
consumed. The tariff rates are as follows:

• For the first 100 units: ₹1.50 per unit


• For the next 200 units (101-300): ₹2.50 per unit
• For units above 300: ₹4.00 per unit

import java.util.Scanner;
public class ElectricityBill {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// read number of units consumed from keyboard
System.out.print("Enter the number of units consumed: ");
int units = scanner.nextInt();
double billAmount = 0.0;
9

// Calculate the bill based on the tariff rates


if (units <= 100) {
billAmount = units * 1.50;
} else if (units <= 200) {
billAmount = (100 * 1.50) + ((units - 100) * 2.50);
} else {
billAmount = (100 * 1.50) + (200 * 2.50) + ((units - 300) * 4.00);
}
// Add the fixed charge to bill Amount
billAmount += 50;
// Display the total bill
System.out.println("Electricity Bill: " + billAmount);
scanner.close();
}
}
==========================
Activity 3: Student has to develop java application for the below problem.

At a University, the Controller of Examinations (COE) wants to calculate the grades of students.
Help COE to develop a java application to determine and display the grades of three students
based on their marks provided as input.

A student is awarded:

• Grade A if marks are greater than 90,


• Grade B if marks are greater than 70,
• Grade C if marks are greater than or equal to 40,
• Grade F otherwise.

==========================
8. Imagine you're developing an educational app for children to learn basic arithmetic. The
app should include a simple calculator with a user-friendly interface.
Requirements:
10

The app should present a menu of arithmetic operations to the child:


Addition
Subtraction
Multiplication
Division
The child should be able to select an operation by tapping the corresponding button.
The app should then prompt the child to enter two numbers.
The calculator should perform the selected operation and display the result.
The app should provide visual feedback and encouragement to the child.
import java.util.Scanner;

public class ChildrensCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice, num1, num2;
float result;

System.out.println("Welcome to the Kids' Calculator!");


System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

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


num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
num2 = scanner.nextInt();

switch (choice) {
case 1:
result = num1 + num2;
System.out.println("Addition :"+ num1 + " + " + num2 + " = " +
result);
break;
case 2:
result = num1 - num2;
11

System.out.println("Subtraction :" + num1 + " - " + num2 + " = "


+ result);
break;
case 3:
result = num1 * num2;
System.out.println(" Multiplication " + num1 + " * " + num2 + " =
" + result);
break;
case 4:
if (num2 == 0) {
System.out.println("Oops! You can't divide by zero.");
} else {
result = (float) num1 / num2;
System.out.println("Division " + num1 + " / " + num2 + " = "
+ result);
}
break;
default:
System.out.println("Invalid choice. Please try again.");
}

scanner.close();
}
}
==========================

You might also like