题目
1.文件读写
public interface FileCopyInter{
public void copyFile(String source, String destination);
}
public class SwitchImpl implements FileCopyInter{
@Override
public void copyFile(String source, String target) {
try {
// 创建输入流,用于读取源文件
FileInputStream fis = new FileInputStream(source);
// 将输入字节流转换为字符流,使用UTF-8编码
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
// 创建输出流,用于写入目标文件
FileOutputStream fos = new FileOutputStream(target);
// 将输出字节流转换为字符流,使用UTF-8编码
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
// 使用BufferedReader和BufferedWriter来提高读写效率
BufferedReader br = new BufferedReader(isr);
BufferedWriter bw = new BufferedWriter(osw);
// 读取源文件内容并写入目标文件
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine(); // 写入一个新行,保持原有格式
}
// 刷新缓冲区,确保所有内容都被写入目标文件
bw.flush();
// 关闭流资源,释放系统资源
bw.close();
br.close();
osw.close();
fos.close();
isr.close();
fis.close();
} catch (Exception e) {
System.out.println("Could not copy file");
e.printStackTrace();
}
}
}
public class FileCopyExample {
public static void main(String[] args) {
String sc="D:\\xz\\homework\\untitled\\Resources\\in.txt";
String tar1="D:\\xz\\homework\\untitled\\Resources\\out1.txt";
FileCopyInter swimpl=new SwitchImpl();
swimpl.copyFile(sc,tar1);
}
}
2.多线程编程
import java.util.Random;
class Account{
int balance;
public Account() {
balance = 0;
}
public synchronized void deposit(int amount) {
System.out.println("***Current balance:" + balance);
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposited " + amount + ", new balance: " + balance);
}
public synchronized void withdraw(int amount) {
System.out.println("***Current balance:" + balance);
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " withdrew " + amount + ", new balance: " + balance);
}
else{
System.out.println(Thread.currentThread().getName() + " tried to withdraw " + amount +
" but there are insufficient funds.");
}
}
}
public class MultiThreadExample {
public static void main(String[] args) {
Account account = new Account();
Thread producer =new Thread(new Runnable() {
@Override
public void run() {
int times=5;
while(times--!=0) {
account.deposit(new Random().nextInt(10) + 1);
try {
Thread.sleep((long) ((Math.random() * 0.5 + 1) * 1000)); // 随机暂停
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread was interrupted: " + e.getMessage());
}
}
}
});
Thread consumer =new Thread(new Runnable() {
@Override
public void run() {
int times=5;
while(times--!=0) {
account.withdraw(new Random().nextInt(10) + 1);
try {
Thread.sleep((long) ((Math.random() * 0.5 + 1) * 1000)); // 随机暂停
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread was interrupted: " + e.getMessage());
}
}
}
});
producer.start();
consumer.start();
}
}
3.图形化编程
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class QuadraticEquationSolver extends JFrame {
private JTextField aField;
private JTextField bField;
private JTextField cField;
private JButton solveButton;
private JTextArea resultArea;
public QuadraticEquationSolver() {
createUI();
}
private void createUI() {
setTitle("一元二次方程求解器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
Container pane = getContentPane();
pane.setLayout(null);
JLabel aLabel = new JLabel("请输入系数a:");
aLabel.setBounds(10, 10, 80, 25);
pane.add(aLabel);
aField = new JTextField(10);
aField.setBounds(100, 10, 80, 25);
pane.add(aField);
JLabel bLabel = new JLabel("请输入系数b:");
bLabel.setBounds(10, 40, 80, 25);
pane.add(bLabel);
bField = new JTextField(10);
bField.setBounds(100, 40, 80, 25);
pane.add(bField);
JLabel cLabel = new JLabel("请输入系数c:");
cLabel.setBounds(10, 70, 80, 25);
pane.add(cLabel);
cField = new JTextField(10);
cField.setBounds(100, 70, 80, 25);
pane.add(cField);
solveButton = new JButton("求解");
solveButton.setBounds(10, 100, 80, 25);
solveButton.addActionListener(new SolveActionListener());
pane.add(solveButton);
resultArea = new JTextArea();
resultArea.setBounds(100, 100, 270, 25);
resultArea.setEditable(false);
pane.add(resultArea);
setVisible(true);
}
private class SolveActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
double a = Double.parseDouble(aField.getText());
double b = Double.parseDouble(bField.getText());
double c = Double.parseDouble(cField.getText());
double[] roots = solveQuadratic(a, b, c);
resultArea.setText("方程的根为: " + roots[0] + " 和 " + roots[1]);
} catch (Exception ex) {
resultArea.setText("输入错误,请检查系数是否正确");
}
}
}
private double[] solveQuadratic(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
return new double[]{Double.NaN, Double.NaN}; // 无实数根
}
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
return new double[]{root1, root2};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new QuadraticEquationSolver();
}
});
}
}
4.网络读写
import java.io.*;
import java.net.*;
//服务端
public class TCPServer {
public static void main(String[] args) {
try {
// 创建服务器端的ServerSocket,监听端口号
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("Server is running and waiting for client connection...");
// 服务器无限循环,等待客户端连接
while (true) {
// 等待接受客户端的连接,此方法会阻塞,直到一个连接建立
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("Client says: " + inputLine);
// 向客户端发送响应
out.println("ok");
// 如果客户端发送了"bye",则结束循环
if ("bye".equalsIgnoreCase(inputLine)) {
break;
}
}
// 关闭连接
in.close();
out.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
//客户端
public class TCPClient {
public static void main(String[] args) {
try {
// 创建客户端的Socket,连接服务器的IP和端口号
Socket socket = new Socket("localhost", 6666);
// 获取输出流,用于向服务器发送数据
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// 获取输入流,用于接收服务器的响应
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 获取标准输入流,用于读取用户输入
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type 'bye' to exit");
// 循环读取用户输入,并发送给服务器
String userInput;
while ((userInput = stdIn.readLine()) != null) {
// 向服务器发送数据
out.println(userInput);
// 读取服务器的响应,并在客户端显示
String fromServer = in.readLine();
System.out.println("Server says: " + fromServer);
// 如果用户输入了"bye",则结束循环
if ("bye".equalsIgnoreCase(userInput)) {
break;
}
}
// 关闭连接
in.close();
out.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Server not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O Error: " + e.getMessage());
}
}
}