java入门实例题型
- 斐波纳契数列
编写一个java程序打印斐波纳契(fibonacci)数列不使用递归和使用递归。
输入: 8
输出: 0 1 1 2 3 5 8 13
public class ex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
for (int i = 0;i < x ;i++){
System.out.print(fi(i)+" ");
}
}
public static int fi (int x){
if( x == 0 || x == 1){
return x;
}
else
return fi(x-1) + fi(x - 2);
}
结果
8
0 1 1 2 3 5 8 13
Process finished with exit code 0
- 素数实例编写一个java程序来判定给定的一个数字是否为素数。
输入: 12
输出:false
输入: 11
输出:true
public class ex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
boolean isprime = true;
int n = (int)Math.sqrt(x);
for ( int i = 2;i <= n;i++){
if(x % i == 0)
isprime = false;
}
System.out.println(isprime);
}
}
结果
11
true
Process finished with exit code 0
12
false
Process finished with exit code 0
- 回文数编写一个java程序断定给定的字符串是否为一个回文数。
输入: 321
输出: false
输入: 12344321
输出: true
public class ex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int n = x;
int sum = 0,m;
boolean ishuiwen = true;
while(x != 0){
m = x % 10;
sum = sum * 10 + m;
x /= 10;
}
if (sum != n)
ishuiwen = false;
System.out.println(ishuiwen);
}
}
结果
321
false
Process finished with exit code 0
12344321
true
Process finished with exit code 0
- 阶乘编写一个java程序来打印数字的阶乘。
输入: 5
输出: 120
public class ex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.println(fac(x));
}
public static int fac(int x){
if(x == 1 || x == 0)
return 1;
else
return x * fac(x - 1);
}
}
结果
5
120
Process finished with exit code 0
- 阿姆斯壮数
编写一个java程序来断定一个数值是否为阿姆斯壮(Armstrong)数。
输入: 153
输出: true
输入: 12
输出: false
public class ex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int n,sum = 0,y = x;
boolean isAmusi = false;
while (x != 0){
n = x % 10;
sum += n*n*n;
x /= 10;
}
if(sum == y){
isAmusi = true;
}
System.out.println(isAmusi);
}
}
结果
153
true
Process finished with exit code 0
12
false
Process finished with exit code 0
- 冒泡排序
编写一个java程序,使用冒泡排序算法对数组元素进行排序。
排序前:1,5,6,8,9,2
排序后:1,2,5,6,8,9
public class ex {
public static void main(String[] args) {
int a []={2,3,4,1,6,7};
int tem;
for(int i = 1;i <= a.length ;i++){
for(int j = 1;j <=a.length - i;j++){
if(a[j - 1] > a[j]){
tem = a[j-1];
a[j-1] = a[j];
a[j] = tem;
}
}
}
for(int i : a){
System.out.print(i+" ");
}
}
}
1 2 3 4 6 7
Process finished with exit code 0
7,选择排序
编写一个java程序,使用选择排序算法对数组元素进行排序。
排序前:1,5,6,8,9,2
排序后:1,2,5,6,8,9
public class ex {
public static void main(String[] args) {
int a []={2,3,4,1,6,7};
int tem,index,smaller;
for(int i = 0;i < a.length;i++){
index = i;
for(int j = i+1;j < a.length;j++){//内循环是为了找出最小数字的索引
if(a[j] < a[index]){
index = j;
}
}
smaller = a[index];
a[index] = a[i];
a[i] = smaller;
}
for(int i : a){
System.out.print(i+" ");
}
}
}
结果
1 2 5 6 8 9
Process finished with exit code 0