Java编程习题集
编写一个Java程序,接受用户输入的两个数,然后计算它们的和并输出结果。
示例代码:
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: " sum);
}
}
编写一个Java程序,找出给定数组中的最大值并输出。
示例代码:
public class FindMaxNumber {
public static void main(String[] args) {
int[] arr = {10, 23, 5, 17, 8};
int max = arr[0];
for (int i = 1; i < arr.length; i ) {
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("Max number in the array: " max);
}
}
编写一个Java程序,判断给定的数是否为素数(只能被1和自身整除的数)。
示例代码:
public class PrimeNumber {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i ) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int n = 17;
if (isPrime(n)) {
System.out.println(n " is a prime number.");
} else {
System.out.println(n " is not a prime number.");
}
}
}
编写一个Java程序,反转给定的字符串。
示例代码:
public class ReverseString {
public static void main(String[] args) {
String str = "Hello, World!";
StringBuilder reversed = new StringBuilder();
for (int i = str.length() 1; i >= 0; i) {
reversed.append(str.charAt(i));
}
System.out.println("Reversed string: " reversed);
}
}