JAVA LAB ANS (1)
JAVA LAB ANS (1)
//1
import java.util.*;
class BankAcc {
int accountNumber;
float accountBalance;
void display() {
if (accountNumber >= -500 && accountNumber <= 500 && accountBalance >= -1000.00 && accountBalance <= 1
System.out.println("true");
} else {
System.out.println("false");
}
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if (!sc.hasNextInt()) {
System.out.println("Invalid input");
return;
}
int accountNumber = sc.nextInt();
if (!sc.hasNextFloat()) {
System.out.println("Invalid input");
return;
}
float accountBalance = sc.nextFloat();
//2
import java.util.Scanner;
class Book {
String title;
String author;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Creating books
Book book1 = new Book(); // Book with default details
String inputTitle = scanner.nextLine();
String inputAuthor = scanner.nextLine();
System.out.println(exists);
}
//3
import java.util.Scanner;
class Student {
String name;
int grade;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if (!sc.hasNextInt()) {
System.out.println("Invalid input");
return;
}
int grade1 = sc.nextInt();
if (!sc.hasNextInt()) {
System.out.println("Invalid input");
return;
}
int grade2 = sc.nextInt();
_____________________________________________________________________________
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
_____________________________________________________________________________
INHERITANCE
//1
import java.util.Scanner;
@Override
public double calculateFinalAmount() {
return amount + (amount * 0.02); // 2% fee
}
}
@Override
public double calculateFinalAmount() {
return amount + 1.00; // $1.00 flat fee
}
}
// Subclass for PayPal payment with no additional fee
class PayPalPayment extends Payment {
public PayPalPayment(double amount) {
super(amount);
}
@Override
public double calculateFinalAmount() {
return amount; // No additional fee
}
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//2,3
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String id = scanner.nextLine();
int numGrades;
try {
numGrades = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid input");
return;
}
// Input grades
int[] grades = new int[numGrades];
for (int i = 0; i < numGrades; i++) {
try {
grades[i] = Integer.parseInt(scanner.nextLine());
if (grades[i] < 0 || grades[i] > 100) {
System.out.println("Invalid input");
return;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input");
return;
}
}
_____________________________________________________________________________
//1,2,3
import java.util.Scanner; import
java.util.regex.Pattern;
interface PaymentMethod
{
}
boolean authorizePayment();
String transactionStatus();
abstract class Payment implements PaymentMethod
{
String paymentType;
public Payment(String paymentType)
{
this.paymentType = paymentType;
}
public abstract void displayPaymentDetails();
}
class CreditCardPayment extends Payment
{
private String cardNumber;
private String cardHolder;
private String expirationDate;
public CreditCardPayment(String cardNumber, String cardHolder, String
expirationDate)
{
super("Credit Card");
this.cardNumber = cardNumber;
this.cardHolder = cardHolder;
this.expirationDate = expirationDate;
}
public boolean isValidCardNumber()
{
}
return Pattern.matches("\\d{4}-\\d{4}-\\d{4}-\\d{4}", cardNumber);
public boolean isValidExpirationDate()
{
return Pattern.matches("(0[1-9]|1[0-2])/\\d{2}", expirationDate);
}
class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
_____________________________________________________________________________
COLLECTION INTERFACE
//1,2,3
import java.util.*; class
Classroom
{
private List<Map<String, String>> attendanceList;
public Classroom()
{
attendanceList = new ArrayList<>();
}
studentName = scanner.nextLine();
String status = scanner.nextLine();
classroom.markAttendance(studentName, status);
classroom.displayAttendance();
}
}
_____________________________________________________________________________
MULTITHREADING
//1
import java.util.Scanner;
@Override
public void run() {
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.printf("Result for dataset %d: Sum = %d, Average = %.2f%n", datasetId, sum, average);
}
}
// Main class
public class DataAnalysisMultithreading {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int s = scanner.nextInt();
}
}
//Input:
2
1
3
10 20 30
2
4
5 15 25 35
//Output:
Result for dataset 1: Sum = 60, Average = 20.00
Result for dataset 2: Sum = 80, Average = 20.00
//2
import java.util.Scanner;
// Class to handle ticket booking
class TicketBookingSystem {
private int totalTickets;
@Override
public void run() {
bookingSystem.bookTicket(userId, ticketsRequested);
}
}
// Main class
class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.close();
}
}
//Input:
10
3
15
24
33
//Output:
User 1: Booking Success for 5 tickets.
User 3: Booking Success for 3 tickets.
User 2: Booking Failed. Not enough tickets available.
Remaining tickets: 2
//3
import java.util.Scanner;
class FileProcessor {
private String filename;
private String content;
try {
readThread.start();
readThread.join(); // Ensure reading completes before transforming
transformThread.start();
transformThread.join(); // Ensure transforming completes before saving
saveThread.start();
saveThread.join(); // Ensure saving completes for final output
} catch (InterruptedException e) {
System.out.println("Processing interrupted for file: " + filename);
}
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
scanner.nextLine(); // Consume newline
}
}
//Input:
2
java1.txt
hello world
java2.txt
multithreading
//Output:
Reading file: java1.txt
Transforming content for file: java1.txt
Saving file: java1.txt with content: HELLO WORLD
Reading file: java2.txt
Transforming content for file: java2.txt
Saving file: java2.txt with content: MULTITHREADING
_____________________________________________________________________________
EXCEPTION HANDLING
//1,2,3
import java.util.Scanner;
int n = scanner.nextInt();
if (divisor == 0) {
System.out.println("Invalid input");
return;
}
double sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
System.out.printf("Average of elements: %.2f\n", sum / n);
} catch (Exception e) {
System.out.println("Invalid input");
} finally {
scanner.close();
}
}
}
//Input:
5
10 20 30 40 50
5
2
_____________________________________________________________________________
SWINGS
//1
package Swings;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public Lab1() {
// Setting up the JFrame
setTitle("Basic Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2, 5, 5));
// Initializing components
JLabel label1 = new JLabel("Enter Number 1:");
textField1 = new JTextField();
JLabel label2 = new JLabel("Enter Number 2:");
textField2 = new JTextField();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
// Parse the numbers from the text fields
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
int result = 0;
//2
package Swings;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public Lab2() {
// Set up the JFrame
setTitle("User Registration Form");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(6, 2, 5, 5));
// Initialize components
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// Get input values
String name = nameField.getText();
String email = emailField.getText();
String phone = phoneField.getText();
String password = new String(passwordField.getPassword());
// Validate inputs
if (!isValidName(name)) {
messageLabel.setText("Error: Invalid name");
} else if (!isValidEmail(email)) {
messageLabel.setText("Error: Invalid email");
} else if (!isValidPhone(phone)) {
messageLabel.setText("Error: Invalid phone number");
} else if (!isValidPassword(password)) {
messageLabel.setText("Error: Password must be at least 8 characters");
} else {
messageLabel.setText("Success: Registration complete!");
}
}
//3
package Swings;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public Lab3() {
// Initialize components
setTitle("To-Do List Application");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(inputPanel, BorderLayout.NORTH);
add(new JScrollPane(taskList), BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
// Add Task Action
addButton.addActionListener(e -> addTask());
// Mark Complete Action
completeButton.addActionListener(e -> markTaskComplete());
// Delete Task Action
deleteButton.addActionListener(e -> deleteTask());
setVisible(true);
}
if (task.isEmpty()) {
JOptionPane.showMessageDialog(this, "Task cannot be empty", "Warning", JOptionPane.WARNING_MESSAGE)
return;
}
if (taskListModel.contains(task)) {
JOptionPane.showMessageDialog(this, "Task already exists", "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
taskListModel.addElement(task);
taskField.setText("");
}