自己定义一个类,有static属性和构造方法,有构造方法重载,有其他方法(方法有对String类型操作)
public class MyClass { // 静态属性 public static String staticProperty = "Static Property"; // 成员变量 private String value; // 构造方法 public MyClass(String value) { this.value = value; } // 构造方法重载 public MyClass(int value) { this.value = String.valueOf(value); } // 其他方法,对字符串类型进行操作 public void manipulateString(String newValue) { this.value += newValue; } // Getter方法 public String getValue() { return value; } } public class Main { public static void main(String[] args) { // 调用不同的构造方法生成两个对象 MyClass obj1 = new MyClass("Hello"); MyClass obj2 = new MyClass(123); // 调用其他方法 obj1.manipulateString(" World"); obj2.manipulateString("456"); // 输出结果 System.out.println("Value of obj1: " + obj1.getValue()); // 输出:Hello World System.out.println("Value of obj2: " + obj2.getValue()); // 输出:123456 // 访问静态属性 System.out.println("Static property: " + MyClass.staticProperty); // 输出:Static Property } }
定义一个Person类,有各种属性和行为,对属性建立setter和getter方法。对其中一个行为进行重载,建立一个TestPerson类,在main函数中建立Person对象,并调用对象的行为
// Person 类 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; } // Getter 和 Setter 方法 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 void introduce() { System.out.println("Hello, I am " + name + ", " + age + " years old, " + gender + "."); } // 重载 introduce 方法 public void introduce(String occupation) { System.out.println("Hello, I am " + name + ", " + age + " years old, " + gender + "."); System.out.println("I am a " + occupation + "."); } } // TestPerson 类 public class TestPerson { public static void main(String[] args) { // 创建 Person 对象 Person person1 = new Person("Alice", 30, "Female"); // 调用对象的行为 person1.introduce(); // 使用重载方法 person1.introduce("software engineer"); // 测试 Getter 和 Setter 方法 System.out.println("Before setting age: " + person1.getAge()); person1.setAge(35); System.out.println("After setting age: " + person1.getAge()); } }
自行定义任意一个抽象的父类,有属性和方法,再自行定义两个子类,子类有不同于父类的属性和方法。同时重写父类的一个方法。用多态的形式调用子类方法,方法中涉及基本类型的包装类。写出Java程序
abstract class Shape { // 属性 protected double area; // 抽象方法 public abstract void calculateArea(); // 方法 public void displayArea() { System.out.println("Area: " + area); } } class Circle extends Shape { // 子类属性 private double radius; // 构造方法 public Circle(double radius) { this.radius = radius; } // 重写父类方法 @Override public void calculateArea() { area = Math.PI * radius * radius; } // 子类方法 public void displayRadius() { System.out.println("Radius: " + radius); } } class Rectangle extends Shape { // 子类属性 private double length; private double width; // 构造方法 public Rectangle(double length, double width) { this.length = length; this.width = width; } // 重写父类方法 @Override public void calculateArea() { area = length * width; } // 子类方法 public void displayDimensions() { System.out.println("Length: " + length + ", Width: " + width); } } public class Main { public static void main(String[] args) { // 使用多态性调用子类方法 Shape circle = new Circle(5.0); circle.calculateArea(); circle.displayArea(); // 输出:Area: 78.53981633974483 // 使用多态性调用子类方法 Shape rectangle = new Rectangle(4.0, 6.0); rectangle.calculateArea(); rectangle.displayArea(); // 输出:Area: 24.0 } }
输入一个日期格式为xxxx-xx-xx,如果格式不正确,抛出一个自定义日期格式异常,如果格式正确,请输出:你输入的2023-01-01是兔年,星期日,然后每隔一秒钟,输出现在是2024年2月26日,**时**分**秒
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; class InvalidDateFormatException extends Exception { public InvalidDateFormatException(String message) { super(message); } } public class Main { public static void main(String[] args) { try { String inputDate = "2023-01-01"; validateDateFormat(inputDate); // 输出输入日期信息 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = dateFormat.parse(inputDate); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); String animal = getChineseZodiac(year); String dayOfWeekString = getDayOfWeekString(dayOfWeek); System.out.println("你输入的" + inputDate + "是" + animal + "年," + dayOfWeekString); // 模拟每隔一秒钟输出当前日期时间 while (true) { Thread.sleep(1000); // 等待1秒 calendar.add(Calendar.SECOND, 1); // 增加1秒 year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.printf("现在是%d年%d月%d日,%02d时%02d分%02d秒%n", year, month, day, hour, minute, second); } } catch (InvalidDateFormatException e) { System.out.println(e.getMessage()); } catch (ParseException | InterruptedException e) { e.printStackTrace(); } } private static void validateDateFormat(String inputDate) throws InvalidDateFormatException { if (!inputDate.matches("\\d{4}-\\d{2}-\\d{2}")) { throw new InvalidDateFormatException("日期格式错误,请输入格式为xxxx-xx-xx的日期。"); } } private static String getChineseZodiac(int year) { String[] zodiacs = {"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"}; return zodiacs[(year - 1900) % 12]; } private static String getDayOfWeekString(int dayOfWeek) { String[] daysOfWeek = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; return daysOfWeek[dayOfWeek - 1]; } }
自定义一个类,类中引用了泛型技术。生成几个自定义类的对象,将对象加入到集合的ArrayList或LinkList,并在集合中删除部分对象,最后在集合中删除对象的全部输出,Java程序
import java.util.ArrayList; import java.util.Iterator; import java.util.List; class CustomClass<T> { private T data; public CustomClass(T data) { this.data = data; } public T getData() { return data; } public void setData(T data) { this.data = data; } } public class Main { public static void main(String[] args) { // 创建自定义类的对象 CustomClass<Integer> obj1 = new CustomClass<>(1); CustomClass<String> obj2 = new CustomClass<>("Hello"); CustomClass<Double> obj3 = new CustomClass<>(3.14); // 创建ArrayList集合 List<CustomClass<?>> list = new ArrayList<>(); // 将对象添加到集合中 list.add(obj1); list.add(obj2); list.add(obj3); // 输出集合中的对象 System.out.println("初始集合中的对象:"); for (CustomClass<?> obj : list) { System.out.println(obj.getData()); } // 删除部分对象 list.remove(obj2); // 输出删除部分对象后的集合 System.out.println("删除部分对象后的集合:"); for (CustomClass<?> obj : list) { System.out.println(obj.getData()); } // 删除集合中的全部对象 list.clear(); // 输出删除全部对象后的集合 System.out.println("删除全部对象后的集合:"); for (CustomClass<?> obj : list) { System.out.println(obj.getData()); } } }
向一个文件输入自己的信息,然后把信息打印出来,打印在终端Java程序
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileIOExample { public static void main(String[] args) { // 文件路径 String filePath = "myInfo.txt"; // 向文件输入信息 writeToFile(filePath, "Name: John Doe\nAge: 25\nOccupation: Developer"); // 从文件读取信息并打印在终端 String fileContent = readFromFile(filePath); System.out.println("File Content:\n" + fileContent); } // 向文件写入信息 private static void writeToFile(String filePath, String content) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) { writer.write(content); } catch (IOException e) { e.printStackTrace(); } } // 从文件读取信息 private static String readFromFile(String filePath) { StringBuilder content = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } } catch (IOException e) { e.printStackTrace(); } return content.toString(); } }
自行设计一个界面,至少包含3个基本的组件,程序包含监听事件,Java程序
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class SimpleGUIExample { public static void main(String[] args) { // 创建 JFrame 实例 JFrame frame = new JFrame("Simple GUI Example"); // 设置关闭操作 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 创建组件 JButton button = new JButton("点击我"); JTextField textField = new JTextField(20); JLabel label = new JLabel("显示区域:"); // 创建面板 JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); // 添加组件到面板 panel.add(textField); panel.add(button); panel.add(label); // 添加面板到框架 frame.getContentPane().add(BorderLayout.CENTER, panel); // 添加按钮点击事件监听器 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 按钮点击时更新标签内容 label.setText("显示区域: " + textField.getText()); } }); // 设置框架大小 frame.setSize(300, 150); // 设置框架可见 frame.setVisible(true); } }
编写多线程程序,用两种方法(继承Thread,实现Runnable,卡里的前,每增加一元,自己的java技能,每秒钟增加一点
class CardThread extends Thread { private int balance = 0; // 初始卡里的金额 private int javaSkill = 0; // 初始Java技能点数 public void run() { while (true) { try { Thread.sleep(1000); // 线程休眠一秒钟 balance++; // 每秒钟卡里的金额增加一元 javaSkill++; // 每秒钟Java技能增加一点 System.out.println("卡里的金额:" + balance + " 元,Java技能:" + javaSkill + " 点"); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ThreadExample { public static void main(String[] args) { CardThread thread = new CardThread(); thread.start(); // 启动线程 } }
class CardRunnable implements Runnable { private int balance = 0; // 初始卡里的金额 private int javaSkill = 0; // 初始Java技能点数 public void run() { while (true) { try { Thread.sleep(1000); // 线程休眠一秒钟 balance++; // 每秒钟卡里的金额增加一元 javaSkill++; // 每秒钟Java技能增加一点 System.out.println("卡里的金额:" + balance + " 元,Java技能:" + javaSkill + " 点"); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class RunnableExample { public static void main(String[] args) { CardRunnable cardRunnable = new CardRunnable(); Thread thread = new Thread(cardRunnable); thread.start(); // 启动线程 } }
用循环语句打印A-Z共26个字母
public class PrintAlphabets { public static void main(String[] args) { // Using a for loop to print A-Z for (char ch = 'A'; ch <= 'Z'; ch++) { System.out.print(ch + " "); } // If you want to print on new lines: /* for (char ch = 'A'; ch <= 'Z'; ch++) { System.out.println(ch); } */ } }
从键盘输入一个整数到变量a,b,c中,然后由小到大的顺序输出
import java.util.Scanner; public class SortNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 输入三个整数 System.out.print("请输入第一个整数 (a): "); int a = scanner.nextInt(); System.out.print("请输入第二个整数 (b): "); int b = scanner.nextInt(); System.out.print("请输入第三个整数 (c): "); int c = scanner.nextInt(); // 关闭输入流 scanner.close(); // 排序并输出 System.out.println("由小到大的顺序输出:"); displaySortedNumbers(a, b, c); } private static void displaySortedNumbers(int a, int b, int c) { int temp; // 使用冒泡排序进行排序 for (int i = 0; i < 2; i++) { for (int j = 0; j < 2 - i; j++) { if (a > b) { temp = a; a = b; b = temp; } if (b > c) { temp = b; b = c; c = temp; } } } // 输出排序后的结果 System.out.println(a + " " + b + " " + c); } }