Java Programming Exercises: Functions, Classes, and Data Structures
Function Implementation
Write a method to determine if an integer is even:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
System.out.println(checkEven(value));
}
public static boolean checkEven(int num) {
return num % 2 == 0;
}
}
2D Vector Class Implementation
Create a two-dimensional vector class with constructors and methods:
import java.util.Scanner;
class TDVector {
private double xCoord;
private double yCoord;
public String toString() {
return "(" + this.xCoord + "," + this.yCoord + ")";
}
public double getX() { return xCoord; }
public void setX(double x) { this.xCoord = x; }
public double getY() { return yCoord; }
public void setY(double y) { this.yCoord = y; }
public TDVector() { this.xCoord = this.yCoord = 0; }
public TDVector(double x, double y) {
this.xCoord = x;
this.yCoord = y;
}
public TDVector(TDVector source) {
this.xCoord = source.xCoord;
this.yCoord = source.yCoord;
}
public TDVector combine(TDVector other) {
return new TDVector(this.xCoord + other.xCoord, this.yCoord + other.yCoord);
}
}
public class Main {
public static void main(String[] args) {
TDVector a = new TDVector();
Scanner sc = new Scanner(System.in);
double x = sc.nextDouble();
double y = sc.nextDouble();
double z = sc.nextDouble();
TDVector b = new TDVector(x, y);
TDVector c = new TDVector(b);
a.setY(z);
System.out.println(a);
System.out.println(b);
System.out.println(c);
c.setX(z);
a = b.combine(c);
System.out.println(a);
System.out.println("b.x=" + b.getX() + " b.y=" + b.getY());
sc.close();
}
}
Book Class Design
Implement a Book class with properties and a method to calculate total price:
import java.util.*;
class Book {
private String title;
private int cost;
private String writer;
private int year;
public Book(String title, int cost, String writer, int year) {
this.title = title;
this.cost = cost;
this.writer = writer;
this.year = year;
}
public int getCost() { return cost; }
public String getTitle() { return title; }
public String getWriter() { return writer; }
public int getYear() { return year; }
}
public class Main {
public static void main(String[] args) {
List<Book> collection = new ArrayList<>();
Scanner input = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
String[] parts = input.nextLine().split(",");
Book item = new Book(parts[0], Integer.parseInt(parts[1]), parts[2], Integer.parseInt(parts[3]));
collection.add(item);
}
System.out.println(computeTotal(collection));
}
public static int computeTotal(List<Book> books) {
int sum = 0;
for(Book b : books) sum += b.getCost();
return sum;
}
}
Override Equals Method
Implement equals method for Point class:
import java.util.Scanner;
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null || getClass() != obj.getClass()) return false;
Point other = (Point) obj;
return x == other.x && y == other.y;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Object p1 = new Point(sc.nextInt(), sc.nextInt());
Object p2 = new Point(sc.nextInt(), sc.nextInt());
System.out.println(p1.equals(p2));
sc.close();
}
}
Right Triangle Implementation
Create a right triangle class implementing IShape interface:
import java.util.Scanner;
import java.text.DecimalFormat;
interface IShape {
double getArea();
double getPerimeter();
}
class RTriangle implements IShape {
private double sideA, sideB;
public RTriangle(double a, double b) {
this.sideA = a;
this.sideB = b;
}
public double getArea() {
return 0.5 * sideA * sideB;
}
public double getPerimeter() {
return sideA + sideB + Math.sqrt(sideA * sideA + sideB * sideB);
}
}
public class Main {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
IShape triangle = new RTriangle(a, b);
System.out.println(formatter.format(triangle.getArea()));
System.out.println(formatter.format(triangle.getPerimeter()));
input.close();
}
}
Array Sorting Check
Check if an array is sorted in ascending order:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[20];
array[0] = input.nextInt();
for (int i = 1; i <= array[0]; i++)
array[i] = input.nextInt();
if (isAscending(array))
System.out.println("The list is already sorted");
else
System.out.println("The list is not sorted");
}
public static boolean isAscending(int[] arr) {
for (int i = 2; i <= arr[0]; i++) {
if (arr[i-1] > arr[i])
return false;
}
return true;
}
}
Matrix Multiplication
Implement matrix multiplication using 2D arrays:
import java.util.Scanner;
class Matrix {
int rows, cols;
int[][] data;
static Scanner reader = new Scanner(System.in);
public static Matrix createMatrix() {
Matrix mat = new Matrix();
mat.rows = reader.nextInt();
mat.cols = reader.nextInt();
mat.data = new int[mat.rows][mat.cols];
for(int i = 0; i < mat.rows; i++) {
for(int j = 0; j < mat.cols; j++) {
mat.data[i][j] = reader.nextInt();
}
}
return mat;
}
public Matrix multiply(Matrix other) {
Matrix result = new Matrix();
result.data = new int[rows][other.cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < other.cols; j++) {
for(int k = 0; k < cols; k++) {
result.data[i][j] += data[i][k] * other.data[k][j];
}
}
}
return result;
}
}
public class Main {
public static void main(String[] args) {
Matrix first = Matrix.createMatrix();
Matrix second = Matrix.createMatrix();
Matrix product = first.multiply(second);
display(product.data);
}
public static void display(int[][] array) {
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
if(j == array[i].length - 1) {
System.out.println(array[i][j]);
} else {
System.out.print(array[i][j] + " ");
}
}
}
}
}
Worker Salary Calculation
Create WorkerList class to calculate total salaries:
import java.util.*;
class WorkerList {
public List<Worker> buildWorkerList() {
Scanner sc = new Scanner(System.in);
List<Worker> workers = new ArrayList<>();
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
String name = sc.next();
double salary = sc.nextDouble();
workers.add(new Worker(name, salary));
}
return workers;
}
public double calculateTotalSalary(List<Worker> workers) {
double total = 0;
for(Worker w : workers) total += w.getSalary();
return total;
}
}
class Worker {
private String name;
private double salary;
public Worker(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() { return name; }
public double getSalary() { return salary; }
public String toString() {
return name + " " + salary;
}
}
public class Main {
public static void main(String[] args) {
WorkerList app = new WorkerList();
List<Worker> list = app.buildWorkerList();
System.out.println(app.calculateTotalSalary(list));
}
}
Generic String List Operations
Implement StringList with QQ number search functionality:
import java.util.*;
class StringList {
public LinkedList<String> buildList(String[] items) {
LinkedList<String> list = new LinkedList<>();
for(String item : items) list.add(item);
return list;
}
public String findMatching(LinkedList<String> list) {
Scanner sc = new Scanner(System.in);
int targetLength = sc.nextInt();
for(String item : list) {
if(item.length() == targetLength) {
return item;
}
}
return "not exist";
}
}
public class Main {
public static void main(String[] args) {
String[] data = {"12345","67891","12347809931","98765432102","67891","12347809933"};
StringList sl = new StringList();
LinkedList<String> qqNumbers = sl.buildList(data);
System.out.println(sl.findMatching(qqNumbers));
}
}
Count Elements by Length
Count QQ numbers with specific digit length:
import java.util.*;
class StringList {
public LinkedList<String> buildList(String[] items) {
LinkedList<String> list = new LinkedList<>();
for(String item : items) list.add(item);
return list;
}
public String countByLength(LinkedList<String> list) {
Scanner sc = new Scanner(System.in);
int targetLength = sc.nextInt();
int count = 0;
for(String item : list) {
if(item.length() == targetLength) {
count++;
}
}
return count > 0 ? String.valueOf(count) : "-1";
}
}
public class Main {
public static void main(String[] args) {
String[] data = {"12345","67891","12347809931","98765432102","67891","12347809932","12347809934"};
StringList sl = new StringList();
LinkedList<String> qqNumbers = sl.buildList(data);
System.out.println(sl.countByLength(qqNumbers));
}
}
Element Removal from List
Remove specified elements from a list:
import java.util.*;
public class Main {
public static List<String> parseStringToList(String input) {
return new ArrayList<>(Arrays.asList(input.split("\\s+")));
}
public static void removeElement(List<String> list, String target) {
list.removeIf(item -> item.equals(target));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
List<String> words = parseStringToList(sc.nextLine());
System.out.println(words);
String toRemove = sc.nextLine();
removeElement(words, toRemove);
System.out.println(words);
}
sc.close();
}
}
Person Sorting Implementation
Sort teachers and students separately:
import java.util.*;
abstract class Person implements Comparable<Person> {
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() { return name; }
public String getGender() { return gender; }
public int getAge() { return age; }
}
class Student extends Person {
private int id;
private String program;
public Student(int id, String name, String gender, int age, String program) {
super(name, gender, age);
this.id = id;
this.program = program;
}
@Override
public int compareTo(Person other) {
return ((Student) other).id - this.id;
}
}
class Teacher extends Person {
private int employeeId;
private String department;
public Teacher(int employeeId, String name, String gender, int age, String department) {
super(name, gender, age);
this.employeeId = employeeId;
this.department = department;
}
@Override
public int compareTo(Person other) {
return this.getAge() - ((Teacher) other).getAge();
}
}
class Utility {
public static void categorize(List<Person> all, List<Teacher> teachers, List<Student> students) {
for(Person p : all) {
if(p instanceof Teacher)
teachers.add((Teacher) p);
else
students.add((Student) p);
}
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = getPeople();
List<Teacher> instructors = new ArrayList<>();
List<Student> learners = new ArrayList<>();
Utility.categorize(people, instructors, learners);
Collections.sort(instructors);
Collections.sort(learners);
displayResults(instructors);
displayResults(learners);
}
public static List<Person> getPeople() {
List<Person> people = new ArrayList<>();
Scanner input = new Scanner(System.in);
int count = Integer.parseInt(input.nextLine());
for(int i = 0; i < count; i++) {
String[] parts = input.nextLine().split(",");
Person person = null;
if(parts[0].equalsIgnoreCase("student"))
person = new Student(Integer.parseInt(parts[1]), parts[2], parts[3], Integer.parseInt(parts[4]), parts[5]);
else if (parts[0].equalsIgnoreCase("teacher"))
person = new Teacher(Integer.parseInt(parts[1]), parts[2], parts[3], Integer.parseInt(parts[4]), parts[5]);
if(person != null) people.add(person);
}
return people;
}
public static void displayResults(List<? extends Person> group) {
for(Person p : group) {
System.out.println(p.getName() + "," + p.getGender() + "," + p.getAge());
}
}
}
Object Equality with Formatting
Override equals method with decimal formatting:
public boolean equals(Object obj) {
if(!(obj instanceof Employee)) return false;
Employee other = (Employee) obj;
if(!super.equals(other)) return false;
boolean companyMatch = (this.company == null && other.company == null) ||
(this.company != null && this.company.equals(other.company));
if(!companyMatch) return false;
DecimalFormat formatter = new DecimalFormat("#.##");
return formatter.format(this.salary).equals(formatter.format(other.salary));
}
Media Rental System
Calculate rental costs for books and DVDs:
import java.util.Scanner;
abstract class Media {
String title;
double dailyRate;
abstract double getDailyRent();
}
class Book extends Media {
double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
this.dailyRate = 0.01 * price;
}
double getDailyRent() {
return dailyRate;
}
}
class DVD extends Media {
public DVD(String title) {
this.title = title;
this.dailyRate = 1.0;
}
double getDailyRent() {
return dailyRate;
}
}
class RentalService {
public static double computeTotal(Media[] items, int duration) {
double total = 0;
for(Media item : items) {
total += item.getDailyRent() * duration;
}
return total;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
Media[] inventory = new Media[count];
for (int i = 0; i < count; i++) {
String type = sc.next();
if (type.equals("book")) {
inventory[i] = new Book(sc.next(), sc.nextDouble());
} else {
inventory[i] = new DVD(sc.next());
}
}
double cost = RentalService.computeTotal(inventory, sc.nextInt());
System.out.printf("%.2f", cost);
}
}
Ticket Abstract Classes
Design ticket hierarchy with different pricing:
import java.util.Scanner;
abstract class Ticket {
int serialNumber;
public Ticket(int number) {
this.serialNumber = number;
}
public abstract int getPrice();
public abstract String toString();
}
class WalkupTicket extends Ticket {
public WalkupTicket(int number) {
super(number);
}
public int getPrice() {
return 50;
}
public String toString() {
return "Number:" + serialNumber + ",Price:" + getPrice();
}
}
class AdvanceTicket extends Ticket {
int daysBefore;
public AdvanceTicket(int number, int days) {
super(number);
this.daysBefore = days;
}
public int getPrice() {
return daysBefore > 10 ? 30 : 40;
}
public String toString() {
return "Number:" + serialNumber + ",Price:" + getPrice();
}
}
class StudentAdvanceTicket extends AdvanceTicket {
int studentHeight;
public StudentAdvanceTicket(int number, int days, int height) {
super(number, days);
this.studentHeight = height;
}
public int getPrice() {
if(studentHeight > 120) {
return daysBefore > 10 ? 20 : 30;
} else {
return daysBefore > 10 ? 10 : 15;
}
}
public String toString() {
return "Number:" + serialNumber + ",Price:" + getPrice();
}
}
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Ticket walkup = new WalkupTicket(input.nextInt());
System.out.println(walkup.toString());
Ticket advance = new AdvanceTicket(input.nextInt(), input.nextInt());
System.out.println(advance.toString());
Ticket student = new StudentAdvanceTicket(input.nextInt(), input.nextInt(), input.nextInt());
System.out.println(student.toString());
}
}