Java Module-1 Practice based Assignment question and solution
Java Module-1 Practice based Assignment question and solution
3. Write a Java program that asks the user to input a series of numbers and then prints
the largest number in the list.
1. Prompt the user for the number of inputs:
2. Enter the values:
3. Find the largest value:
4. Display the largest value as result:
Program:
import java.util.Scanner;
public class MinMaxArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
}
}
(OR)
import java.util.Arrays;
import java.util.Scanner;
public class MinMaxArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Find the smallest and largest values using Arrays class methods
int smallest = Arrays.stream(numbers).min().getAsInt();
int largest = Arrays.stream(numbers).max().getAsInt();
scanner.close();
}
}
4. In an Inventory Management System for a store, the system allows the user to input
the prices of 5 different products using array. The program calculates the total price,
the highest price, and the lowest price of the products.
Program:
import java.util.Scanner;
public class InventoryManagement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double[] prices = new double[5];
System.out.println("Enter the prices of 5 different products:");
for (int i = 0; i < prices.length; i++) {
System.out.print("Enter price of product " + (i + 1) + ": ");
prices[i] = scanner.nextDouble();
}
double totalPrice = 0;
double highestPrice = prices[0];
double lowestPrice = prices[0];
}
}
5. Write a Java program that checks if a given number is prime or not by using a for
loop.
Program:
import java.util.Scanner;
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}
9. Write a program that generates the Fibonacci series using a recursive method.
Program:
public class Fibonacci {
public static void main(String[] args) {
int n = 10; // Print first 10 Fibonacci numbers
System.out.println("Fibonacci series:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
if (original == reversed) {
System.out.println(original + " is a palindrome.");
} else {
System.out.println(original + " is not a palindrome.");
}
}
}
11. Write a method that calculates the sum of digits of a given number.
Program:
import java.util.Scanner;
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
17. Write a program that prints a pattern of numbers (e.g., a triangle of numbers) using
nested for loops.
1
12
123
1234
12345
Program:
public class NumberPattern {
public static void main(String[] args) {
// Number of rows for the pattern
int rows = 5;
// Outer loop for each row
for (int i = 1; i <= rows; i++) {
// Inner loop to print numbers for each row
for (int j = 1; j <= i; j++) {
System.out.print(j); // Print number without new line
}
System.out.println(); // Move to the next line after each row
}
}
}
18. Write a program to print a right-angled triangle pattern of stars using nested for
loops.
*
**
***
****
*****
******
Program:
public class RightAngledTriangle {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
19. Write a program that prints a pyramid of stars (*) with a given number of rows using
a for loop.
*
**
***
****
*****
******
Program:
public class Pyramid {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; i++) {
for (int j = i; j < rows; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i * 2 - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
20. Write a Java program using a do-while loop that simulates a simple ATM system.
The program should:
1. Prompt the user to enter their PIN code.
2. Allow the user to enter the PIN multiple times if the correct one is not
entered (maximum of 3 attempts).
If the correct PIN is entered, the program should display a welcome message. If
the wrong PIN is entered 3 times, the program should display a "Card Blocked"
message and exit.
Program:
import java.util.Scanner;
public class ATMSystem {
public static void main(String[] args) {
final int CORRECT_PIN = 1234;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
int enteredPin; // Variable to store entered PIN
do {
System.out.print("Enter your PIN: ");
enteredPin = scanner.nextInt(); // Read the entered PIN
if (enteredPin == CORRECT_PIN) {
System.out.println("Welcome to your ATM account!");
break; // Exit the loop if the PIN is correct
} else {
attempts++; // Increment the number of attempts
if (attempts < 3) {
System.out.println("Incorrect PIN. You have " + (3 - attempts) + " attempts
left.");
}
}
} while (attempts < 3); // Continue the loop until 3 attempts are reached
if (attempts == 3) {
System.out.println("Card Blocked. Too many incorrect attempts.");
}
}
}
21. Write a Java program using a switch statement to simulate a restaurant menu. The
program should:
1. Display the following options:
1: View Menu
2: Order Food
3: View Bill
4: Exit
2. For each choice:
Option 1: Display available food items.
Option 2: Prompt for a food order and confirm it.
Option 3: Display a placeholder bill.
Option 4: Exit the program.
Invalid input: Show an error message and prompt again.
Program:
import java.util.Scanner;
public class RestaurantMenu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
// Display the menu
System.out.println("\nRestaurant Menu:");
System.out.println("1: View Menu");
System.out.println("2: Order Food");
System.out.println("3: View Bill");
System.out.println("4: Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
// View the menu
System.out.println("\nAvailable Food Items:");
System.out.println("1. Burger");
System.out.println("2. Pizza");
System.out.println("3. Pasta");
System.out.println("4. Salad");
break;
case 2:
// Order food
System.out.print("Enter your food choice (1-4): ");
int foodChoice = scanner.nextInt();
System.out.println("You have ordered item " + foodChoice + ".");
break;
case 3:
// View bill (Placeholder)
System.out.println("\nBill: ");
System.out.println("Burger - 500.00");
System.out.println("Pizza - 600.00");
System.out.println("Pasta - 450.00");
System.out.println("Salad - 200.00");
System.out.println("Total: 1750.00");
break;
case 4:
// Exit the program
System.out.println("Thank you for visiting!");
break;
default:
// Invalid input
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4); // Loop until the user selects option 4 to exit
}
}
22. Write a program that checks if a given year is a leap year or not using conditional
statements.
Program:
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = sc.nextInt();
// Constructor 1: No parameters
public Book() {
title = "Unknown";
author = "Unknown";
price = 0.0;
}
System.out.println("Book 1 Details:");
book1.displayDetails();
System.out.println("\nBook 2 Details:");
book2.displayDetails();
System.out.println("\nBook 3 Details:");
book3.displayDetails();
}
}
Design a class called Student to represent the details of a student. The class should include the following
attributes:
Student ID
Name of the Student
Branch
Year
Location
College Name
Use a constructor to assign initial values to these attributes. Additionally, include methods to:
1. Calculate the average marks of the student across 6 subjects.
2. Calculate the student's attendance percentage.
Program:
class Student {
// Attributes
String studentId;
String name;
String branch;
String year;
String location;
String collegeName;
public Student(String studentId, String name, String branch, String year, String location,
String collegeName) {
this.studentId = studentId;
this.name = name;
this.branch = branch;
this.year = year;
this.location = location;
this.collegeName = collegeName;
}
public double calculateAverageMarks(int[] marks) {
int sum = 0;
for (int mark : marks) {
sum += mark;
}
return (double) sum / marks.length;
}
public double calculateAttendancePercentage(int attendedClasses, int totalClasses) {
return ((double) attendedClasses / totalClasses) * 100;
}
}
public class StudentDetails {
public static void main(String[] args) {
// Creating a Student object
Student student = new Student("S123", "John Doe", "Computer Science", "2nd", "New
York", "XYZ University");
int[] marks = {85, 90, 78, 88, 92, 79};
int attendedClasses = 45;
int totalClasses = 50;
double averageMarks = student.calculateAverageMarks(marks);
System.out.println("Average Marks: " + averageMarks);
double attendancePercentage = student.calculateAttendancePercentage(attendedClasses,
totalClasses);
System.out.println("Attendance Percentage: " + attendancePercentage + "%");
}
}