JAVA十道题基础训练题
时间: 2023-09-08 20:14:46 浏览: 129
1. 编写一个 Java 程序,在控制台输出“Hello World!”
```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
```
2. 编写一个 Java 程序,求一个整数数组中的最大值和最小值
```java
public class MaxMin {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int max = arr[0];
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
System.out.println("最大值:" + max);
System.out.println("最小值:" + min);
}
}
```
3. 编写一个 Java 程序,计算从 1 到 100 的所有整数的和
```java
public class Sum {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("总和:" + sum);
}
}
```
4. 编写一个 Java 程序,判断一个整数是否为质数
```java
public class PrimeNumber {
public static void main(String[] args) {
int num = 7;
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + "是质数");
} else {
System.out.println(num + "不是质数");
}
}
}
```
5. 编写一个 Java 程序,判断一个字符串是否为回文字符串
```java
public class Palindrome {
public static void main(String[] args) {
String str = "level";
boolean isPalindrome = true;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(str + "是回文字符串");
} else {
System.out.println(str + "不是回文字符串");
}
}
}
```
6. 编写一个 Java 程序,将一个字符串中的所有空格替换为“%20”
```java
public class ReplaceSpace {
public static void main(String[] args) {
String str = "Hello World";
String newStr = str.replaceAll(" ", "%20");
System.out.println(newStr);
}
}
```
7. 编写一个 Java 程序,将一个字符串反转
```java
public class ReverseString {
public static void main(String[] args) {
String str = "abcdefg";
StringBuilder sb = new StringBuilder(str);
sb.reverse();
System.out.println(sb.toString());
}
}
```
8. 编写一个 Java 程序,将一个数组中的元素顺序颠倒
```java
public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int[] newArr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
newArr[arr.length - 1 - i] = arr[i];
}
System.out.println(Arrays.toString(newArr));
}
}
```
9. 编写一个 Java 程序,输出九九乘法表
```java
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "×" + i + "=" + j * i + "\t");
}
System.out.println();
}
}
}
```
10. 编写一个 Java 程序,求斐波那契数列中的第 n 项
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 7;
int[] arr = new int[n];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < arr.length; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
System.out.println("第" + n + "项:" + arr[n - 1]);
}
}
```
阅读全文