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

Java

The document provides Java code solutions for various programming tasks including calculating the perimeter and area of a circle, creating a Shape class with a Rectangle subclass, handling odd number exceptions, building a simple calculator, and developing a number guessing game. Each solution includes input handling, validation, and output formatting. The document also contains example outputs for each program.

Uploaded by

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

Java

The document provides Java code solutions for various programming tasks including calculating the perimeter and area of a circle, creating a Shape class with a Rectangle subclass, handling odd number exceptions, building a simple calculator, and developing a number guessing game. Each solution includes input handling, validation, and output formatting. The document also contains example outputs for each program.

Uploaded by

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

1.

Complete the code segment to find the perimeter and area of a


circle given a value of radius. You should use Math.Pl constant
in your program. If radius is zero or less than zero then print"
please enter non zero positive number".

Solution: import java.util.Scanner;

public class Circle { public static


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

// Input the radius


System.out.print("Enter the radius of
the circle: "); double radius =
scanner.nextDouble();

if (radius <= 0) {
System.out.println("Please enter a
non-zero positive number."); } else
{ // Calculate perimeter and area
double perimeter = 2 * Math.PI*
radius; double area = Math.PI*
radius * radius;

// Print the results


System.out.printf("Perimeter of the
circle: %.2f%n", perimeter);
System.out.printf("Area of the

circle: %.2f%n", area); }

scanner.close(); } }

Explanation :
1. Input Handling: The radius is read from the user.

2. Validation: Check if the radius is zero or negative. If itis,


print an error message

Output: Display the results using formatted output.


2. Write a Java program to create a class called Shape with a
method called getArea(). Create a subclass called
Rectangle that overrides the getArea() method to calculate the area
of a rectangle.

Solution :

|/ Base class class


Shape
{
|/ Method to be overridden public
double getArea)
{
return 0; I/ Default implementation
}
|| Subclass class Rectangle extends
Shape
{
private double width;
private double height;
|/ Constructor to initialize width and height
public Rectangle(double width, double
height) { this.width = width;
this.height height;
|/ Overriding the getArea method
@Override public double getArea) return width * height;
//Area of rectangle
}
}
|/ Main class to test the functionality public class Main
{ public static void main(Stringl] args)
{
|/ Create a Rectangle object Rectangle rectangle = new
Rectangle(5.0, 3.0);
|/ Calculate and print the area
System.out.println("Area of the rectangle:" +
rectangle.getArea) ); }

Output:
Area of the rectangle: 15.0

3. Write a Java program to create a method that takes an

Solution :

// Custom exception class class


OddNumberException extends
Exception
public OddNumberException(String message)
super(message);
} public class Main
|/ Method that checks if the number is odd public
static void checkEven(int number) throws
OddNumberException if (number %2
!= 0) throw new
OddNumberException("The number " + number +
" is odd.");
}
el
s
e
}
System.out.println ("The number
"+ number + " is even."); public static void
main(String] args)
{
// Test the method with different
numbers
int[] numbers = {2, 3, 4, 5, 6};
for (int number: numbers)
{
t
r
y
{
checkEven(number);
}
catch (OddNumberExceptione)
{
System.out.println(e.getMessage) );
}
}
}
}
Output:
The number 2 is even. The number
3 is odd.
The number 4 is even. The number
5 is odd.
The number 6 is even.

4. Create a simple calculator that can perform basic Solution


:

import java.util.InputMismatchException; import


java.util.Scanner;
public class SimpleCalculator
{
public static void main(Stringl args)
{
Scanner scanner = new
Scanner(System.in); boolean continueCalculation
= true; while
(continueCalculation)
{
t
r
y
}
System.out.println("Welcome to the
Simple Calculator!");
System.out.print("Please enter the
first number: "); double numl =
scanner.nextDouble);
System.out.print("Please enter the
second number: "); double num2 =
scanner.nextDouble();
System.out.println ("Choose an operation:");
System.out.println("1. Addition
(+)"); System.out.println("2.
Subtraction (-)");
System.out.println("3.
Multiplication ()");
System.out.println("4. Division
/)"); int choice =
scanner.nextlnt0; double
result;
switch (choice)
{ c
as e
1:
result = num1 + num2;
System.out.println("Result: " + num1+" + "+
num2 +" =" + result); break; Case
2:
result = num1-num2;
System.out.println("Result: " + num1 +" - "+ num2 +
"= "+ result); break;
case 3:
result = num1 *num2;
System.out.println("Result: " + num1+" *
" + num2 +"= " + result); break;
String response =
Scanner.next();
ContinueCalculation = response.equalslgnore Case
("yes");
}
}
System.out.println("Thank you for using the Simple
Calculator!"); Scanner.close):
}
Output:
Run
Copy code
Welcome to the Simple Calculator! Please enter the
first number: 10
Please enter the second number: 5 Choose an
operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication ()
4. Division (/)
1
Result:10.0 + 5.0 = 15.0 Do you want to perform
another calculation?
(yes/No):

Output:
Run
Copy code
Welcome to the Simple Calculator!
Please enter the first number: 10
Please enter the second number: 5 Choose
an operation:
5. Addition (+)
6. Subtraction (-)
7. Multiplication ()
8. Division (/)
1
Result:10.0 + 5.0 = 15.0 Do you want to perform
another calculation?
(yes/No):

5. Create a number guessing game that generates a


random number and shows a prompt for the user to
guess the number provided feedback (too high or too
low).
Solution :
import java.util. Random;
import java.util.Scanner;
public class NumberGuessingGame
{

public static void main(Stringll args)


{
Scanner scanner = new
Scanner(System.in);
Random random= new Random();
// Generate a random number between l and
100 int
randomNumber =
random.nextint(100) + 1; int
userGuess = 0;
int attempts = 0;
System.out.println("Welcome to the Number
Guessing Game!");
System.out.println("l have selected a number
between 1 and 100. Try to guess
it!");
// Loop until the user guesses the
Correct number while
(userGuess != randomNumber)
{
System.out.print("Enter your guess:
");
try
{
userGuess =
scanner.nextlnt(0;
attemptS++;
if (userGuess < 1||
userGuess > 100)
{
System.out.println("Please guess a number between 1
and 100.");
} else if
(userGuess < randomNumber)
{
System.out.println("Too low!
Try again.");
} else if
(userGuess >
randomNumber)
{
System.out.println("Too high!
Try again.");
}else
{
System.out.println("Congratulations! You've guessed the
number " +randomNumber + " in
" + attempts +"
attempts.");
}
}
catch (EXception e)
{
System.out.println("Invalid input. Please enter a
number between 1 and
100.");
Scanner.next(); // Clear the invalid
input
}
}
Scanner.close) ;
}
}
Output:
Run
Copy code
Welcome to the Number Guessing Game!
I have selected a number between 1 and 100.
Try to guess it! Enter
your guess: 50 Too low!
Try again. Enter your
guess: 75 Too high! Try
again. Enter your guess:
60 Too low! Try again.
Enter your guess: 65
Congratulations! You've guessed the number 65 in 4
attempts.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy