给我100道JAVA编程练习题,从基础到高级,从简单到复杂,最好带有参考答案,有答案的最好带上答案
时间: 2023-03-19 15:22:29 浏览: 306
好的,以下是一些从基础到高级、从简单到复杂的Java编程练习题,包含参考答案:
1. 编写一个程序,计算并输出1到100之间所有整数的和。
答案:
```
public class SumOfNumbers {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("The sum of numbers from 1 to 100 is " + sum);
}
}
```
2. 编写一个程序,输出100以内的所有偶数。
答案:
```
public class EvenNumbers {
public static void main(String[] args) {
for (int i = 2; i <= 100; i += 2) {
System.out.println(i);
}
}
}
```
3. 编写一个程序,输出用户输入的整数是否为质数。
答案:
```
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int num = scanner.nextInt();
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
```
4. 编写一个程序,输出用户输入的字符串中的单词数。
答案:
```
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String str = scanner.nextLine();
String[] words = str.split("\\s+");
int count = words.length;
System.out.println("The number of words in the string is " + count);
}
}
```
5. 编写一个程序,实现一个简单的计算器,可以进行加、减、乘、除四种运算。
答案:
```
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number:");
double num1 = scanner.nextDouble();
System.out.println("Enter the second number:");
double num2 = scanner.nextDouble();
System.out.println("Enter the operator (+, -, *, /):");
char operator = scanner.next().charAt(0);
double result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator.");
return;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
}
}
```
6. 编写一个程序,实现一个简单的登录系统,要求用户输入用户名和密码,如果用户名和密码正确则
阅读全文