java基础考试编程题
Java基础编程练习题
编写一个Java程序,计算并输出1到100之间所有偶数的和。
解答:
public class EvenSum {
public static void main(String[] args) {
int sum = 0;
for (int i = 2; i <= 100; i = 2) {
sum = i;
}
System.out.println("1到100之间所有偶数的和为:" sum);
}
}
编写一个Java程序,计算并输出1到n之间所有整数的乘积。
解答:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个正整数n:");
int n = scanner.nextInt();
int product = 1;
for (int i = 1; i <= n; i ) {
product *= i;
}
System.out.println("1到" n "之间所有整数的乘积为:" product);
}
}
编写一个Java程序,判断一个整数是否是质数。
解答:
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int n = scanner.nextInt();
boolean isPrime = true;
if (n <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(n); i ) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(n "是质数");
} else {
System.out.println(n "不是质数");
}
}
}
编写一个Java程序,求解斐波那契数列的第n项。
解答:
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个正整数n:");
int n = scanner.nextInt();
if (n <= 0) {
System.out.println("输入的n必须是正整数");
} else {
int a = 0;
int b = 1;
for (int i = 2; i <= n; i ) {
int temp = a b;
a = b;
b = temp;
}
System.out.println("斐波那契数列的第" n "项是:" b);
}
}
}
编写一个Java程序,判断一个字符串是否是回文字符串。
解答:
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个字符串:");
String str = scanner.nextLine();
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 "不是回文字符串");
}
}
}