📅  最后修改于: 2023-12-03 15:16:37.279000             🧑  作者: Mango
欢迎来到Java目录-编程示例!这是一个为Java程序员提供的示例代码集合,旨在帮助您快速入门和提升Java编程技能。下面是一些常见的Java编程示例,它们覆盖了各种主题和应用场景。
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
int a = 10; // 变量
final int MAX_VALUE = 100; // 常量
int num = 5;
if (num > 0) {
System.out.println("正数");
} else if (num < 0) {
System.out.println("负数");
} else {
System.out.println("零");
}
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
int j = 0;
do {
System.out.println(j);
j++;
} while (j < 5);
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
Person person = new Person("Alice", 25);
person.sayHello();
public class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age);
this.school = school;
}
public void study() {
System.out.println("I am studying at " + school);
}
}
Student student = new Student("Bob", 20, "XYZ University");
student.sayHello();
student.study();
public interface Drawable {
void draw();
}
public class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle");
}
}
Circle circle = new Circle();
circle.draw();
try {
int result = divide(10, 0);
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("除数不能为零");
}
public int divide(int dividend, int divisor) throws ArithmeticException {
if (divisor == 0) {
throw new ArithmeticException("除数不能为零");
}
return dividend / divisor;
}
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
int number = scanner.nextInt();
System.out.println("您输入的整数是:" + number);
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
File file = new File("example.txt");
try (FileWriter writer = new FileWriter(file)) {
writer.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
以上只是一些Java编程示例的概览,希望能给您提供一些参考和启发。您可以根据自己的需求进一步学习和开发更复杂的Java应用程序。祝您编程愉快!