简单的一些 java 代码
时间: 2023-05-30 12:08:05 浏览: 90
1. 输出 Hello World:
```
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
```
2. 计算两个数的和:
```
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = input.nextInt();
System.out.print("Enter second number: ");
int num2 = input.nextInt();
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is " + sum);
}
}
```
3. 判断一个数是奇数还是偶数:
```
import java.util.Scanner;
public class CheckOddEven {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
}
}
```
4. 计算阶乘:
```
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println(num + "! = " + factorial);
}
}
```
5. 判断一个数是否是质数:
```
import java.util.Scanner;
public class CheckPrime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
boolean isPrime = true;
if (num < 2) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + " is prime");
} else {
System.out.println(num + " is not prime");
}
}
}
```
阅读全文