引言Java作为一种广泛应用的编程语言,其强大的功能和灵活性使其成为开发者的首选。然而,在实际编程过程中,开发者往往会遇到各种难题,特别是在解决复杂算法问题时。本文将深入解析400道实战作业题,帮助读...
Java作为一种广泛应用的编程语言,其强大的功能和灵活性使其成为开发者的首选。然而,在实际编程过程中,开发者往往会遇到各种难题,特别是在解决复杂算法问题时。本文将深入解析400道实战作业题,帮助读者破解Java编程难题,提升编程技能。
public class MaxMinFinder { public static void main(String[] args) { int[] array = {3, 5, 1, 2, 4, 8}; int max = array[0]; int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } if (array[i] < min) { min = array[i]; } } System.out.println("Max: " + max + ", Min: " + min); }
}public class StringReverser { public static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } public static void main(String[] args) { String original = "Hello, World!"; String reversed = reverseString(original); System.out.println("Original: " + original + ", Reversed: " + reversed); }
}public class LinkedList { private Node head; private static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } public void insert(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } public boolean delete(int data) { if (head == null) { return false; } if (head.data == data) { head = head.next; return true; } Node current = head; while (current.next != null) { if (current.next.data == data) { current.next = current.next.next; return true; } current = current.next; } return false; } public Node search(int data) { Node current = head; while (current != null) { if (current.data == data) { return current; } current = current.next; } return null; } public void printList() { Node current = head; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { LinkedList list = new LinkedList(); list.insert(1); list.insert(2); list.insert(3); list.printList(); list.delete(2); list.printList(); Node node = list.search(3); System.out.println("Found: " + (node != null ? node.data : "Not found")); }
}public class Stack { private Node top; private static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } public void push(int data) { Node newNode = new Node(data); newNode.next = top; top = newNode; } public int pop() { if (top == null) { throw new IllegalStateException("Stack is empty"); } int data = top.data; top = top.next; return data; } public boolean isEmpty() { return top == null; } public static void main(String[] args) { Stack stack = new Stack(); stack.push(1); stack.push(2); stack.push(3); while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); } System.out.println(); }
}
public class Queue { private Node front; private Node rear; private static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } public void enqueue(int data) { Node newNode = new Node(data); if (rear == null) { front = rear = newNode; } else { rear.next = newNode; rear = newNode; } } public int dequeue() { if (front == null) { throw new IllegalStateException("Queue is empty"); } int data = front.data; front = front.next; if (front == null) { rear = null; } return data; } public boolean isEmpty() { return front == null; } public static void main(String[] args) { Queue queue = new Queue(); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); while (!queue.isEmpty()) { System.out.print(queue.dequeue() + " "); } System.out.println(); }
}public class BinaryTree { private Node root; private static class Node { int data; Node left; Node right; Node(int data) { this.data = data; this.left = null; this.right = null; } } public void insert(int data) { root = insertRecursive(root, data); } private Node insertRecursive(Node current, int data) { if (current == null) { return new Node(data); } if (data < current.data) { current.left = insertRecursive(current.left, data); } else if (data > current.data) { current.right = insertRecursive(current.right, data); } return current; } public boolean search(int data) { return searchRecursive(root, data) != null; } private Node searchRecursive(Node current, int data) { if (current == null) { return null; } if (data == current.data) { return current; } return data < current.data ? searchRecursive(current.left, data) : searchRecursive(current.right, data); } public void delete(int data) { root = deleteRecursive(root, data); } private Node deleteRecursive(Node current, int data) { if (current == null) { return null; } if (data == current.data) { if (current.left == null && current.right == null) { return null; } if (current.right == null) { return current.left; } if (current.left == null) { return current.right; } int smallestValue = findSmallestValue(current.right); current.data = smallestValue; current.right = deleteRecursive(current.right, smallestValue); return current; } if (data < current.data) { current.left = deleteRecursive(current.left, data); return current; } current.right = deleteRecursive(current.right, data); return current; } private int findSmallestValue(Node root) { return root.left == null ? root.data : findSmallestValue(root.left); } public void printInOrder() { printInOrderRecursive(root); } private void printInOrderRecursive(Node node) { if (node != null) { printInOrderRecursive(node.left); System.out.print(node.data + " "); printInOrderRecursive(node.right); } } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.insert(5); tree.insert(3); tree.insert(7); tree.insert(2); tree.insert(4); tree.insert(6); tree.insert(8); tree.printInOrder(); System.out.println(); tree.delete(3); tree.printInOrder(); System.out.println(); System.out.println("Search 4: " + tree.search(4)); }
}public class Graph { private Map> adjList; public Graph() { adjList = new HashMap<>(); } public void addEdge(int src, int dest) { adjList.computeIfAbsent(src, k -> new ArrayList<>()).add(dest); adjList.computeIfAbsent(dest, k -> new ArrayList<>()).add(src); } public void dfs(int start) { Set visited = new HashSet<>(); dfsRecursive(start, visited); } private void dfsRecursive(int node, Set visited) { visited.add(node); System.out.print(node + " "); List neighbors = adjList.get(node); if (neighbors != null) { for (int neighbor : neighbors) { if (!visited.contains(neighbor)) { dfsRecursive(neighbor, visited); } } } } public void bfs(int start) { Set visited = new HashSet<>(); Queue queue = new LinkedList<>(); queue.add(start); visited.add(start); while (!queue.isEmpty()) { int node = queue.poll(); System.out.print(node + " "); List neighbors = adjList.get(node); if (neighbors != null) { for (int neighbor : neighbors) { if (!visited.contains(neighbor)) { queue.add(neighbor); visited.add(neighbor); } } } } } public static void main(String[] args) { Graph graph = new Graph(); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); graph.addEdge(2, 4); graph.addEdge(3, 4); graph.addEdge(4, 5); System.out.println("DFS: "); graph.dfs(0); System.out.println(); System.out.println("BFS: "); graph.bfs(0); }
} Person类,包含姓名、年龄和性别属性,以及构造函数、getters和setters。public class Person { private String name; private int age; private String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public static void main(String[] args) { Person person = new Person("Alice", 30, "Female"); System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Gender: " + person.getGender()); }
}Animal类,包含eat和sleep方法。然后定义一个Dog类继承自Animal类,并添加一个bark方法。public class Animal { public void eat() { System.out.println("Eating..."); } public void sleep() { System.out.println("Sleeping..."); }
}
public class Dog extends Animal { public void bark() { System.out.println("Barking..."); } public static void main(String[] args) { Animal animal = new Dog(); animal.eat(); animal.sleep(); ((Dog) animal).bark(); }
}Comparable接口,包含一个compareTo方法。然后定义一个Person类实现Comparable接口,并按年龄排序。public interface Comparable { int compareTo(T o);
}
public class Person implements Comparable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int compareTo(Person other) { return Integer.compare(this.age, other.age); } public static void main(String[] args) { List people = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Charlie", 20)); Collections.sort(people); for (Person person : people) { System.out.println(person.name + " - " + person.age); } }
} public class Division { public static void main(String[] args) { try { int result = 10 / 0; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("ArithmeticException: " + e.getMessage()); } }
}Runnable接口实现一个简单的多线程程序,打印数字从1到10。public class MultiThreadedExample implements Runnable { private static final int NUM_THREADS = 5; private static final Object lock = new Object(); public static void main(String[] args) { for (int i = 0; i < NUM_THREADS; i++) { new Thread(new MultiThreadedExample()).start(); } } @Override public void run() { synchronized (lock) { for (int i = 1; i <= 10; i++) { System.out.println(Thread.currentThread().getName() + " - " + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
}import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "username"; String password = "password"; try (Connection connection = DriverManager.getConnection(url, user, password)) { String query = "SELECT * FROM employees"; try (PreparedStatement statement = connection.prepareStatement(query); ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } } } catch (SQLException e) { e.printStackTrace(); } }
}import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SQLExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "username"; String password = "password"; try (Connection connection = DriverManager.getConnection(url, user, password)) { // Insert String insertQuery = "INSERT INTO employees (name, age) VALUES (?, ?)"; try (PreparedStatement statement = connection.prepareStatement(insertQuery)) { statement.setString(1, "Alice"); statement.setInt(2, 25); int rowsAffected = statement.executeUpdate(); System.out.println("Rows affected: " + rowsAffected); } // Update String updateQuery = "UPDATE employees SET age = ? WHERE name = ?"; try (PreparedStatement statement = connection.prepareStatement(updateQuery)) { statement.setInt(1, 26); statement.setString(2, "Alice"); int rowsAffected = statement.executeUpdate(); System.out.println("Rows affected: " + rowsAffected); } // Delete String deleteQuery = "DELETE FROM employees WHERE name = ?"; try (PreparedStatement statement = connection.prepareStatement(deleteQuery)) { statement.setString(1, "Alice"); int rowsAffected = statement.executeUpdate(); System.out.println("Rows affected: " + rowsAffected); } } catch (SQLException e) { e.printStackTrace(); } }
}”`java // Server.java import java.io.; import java.net.;
public class Server {
public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(12345); System.out.println("Server is listening on port 12345"); Socket socket = serverSocket.accept(); System.out.println("Client connected"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received: "