JAVA模拟试题及答案

Sun 公司在推出 Java 之际就将其作为一种开放的技术。那么java作为一种编程语言,你对java编程题有把握吗?下面跟yjbys小编一起来看看吧!

JAVA模拟试题及答案

  【程序1】

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

这是一个菲波拉契数列问题

public class lianxi01 {

public static void main(String[] args) {

tln("第1个月的兔子对数: 1");

tln("第2个月的兔子对数: 1");

int f1 = 1, f2 = 1, f, M=24;

for(int i=3; i<=M; i++) {

f = f2;

f2 = f1 + f2;

f1 = f;

tln("第" + i +"个月的兔子对数: "+f2);

}

}

}

  【程序2】

题目:判断101-200之间有多少个素数,并输出所有素数。

程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除, 则表明此数不是素数,反之是素数。

public class lianxi02 {

public static void main(String[] args) {

int count = 0;

for(int i=101; i<200; i+=2) {

boolean b = false;

for(int j=2; j<=(i); j++)

{

if(i % j == 0) { b = false; break; }

else { b = true; }

}

if(b == true) {count ++;tln(i );}

}

tln( "素数个数是: " + count);

}

}

  【程序3】

题目:打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个 "水仙花数 ",因为153=1的三次方+5的三次方+3的'三次方。

public class lianxi03 {

public static void main(String[] args) {

int b1, b2, b3;

for(int m=101; m<1000; m++) {

b3 = m / 100;

b2 = m % 100 / 10;

b1 = m % 10;

if((b3*b3*b3 + b2*b2*b2 + b1*b1*b1) == m) {

tln(m+"是一个水仙花数"); }

}

}

}

  【程序4】

题目:利用条件运算符的嵌套来完成此题:学习成绩> =90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。

import .*;

public class lianxi05 {

public static void main(String[] args) {

int x;

char grade;

Scanner s = new Scanner();

t( "请输入一个成绩: ");

x = Int();

grade = x >= 90 ? ’A’

: x >= 60 ? ’B’

:’C’;

tln("等级为:"+grade);

}

}

  【程序5】

题目:输入两个正整数m和n,求其最大公约数和最小公倍数。

/**在循环中,只要除数不等于0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,如此循环直到较小的数的值为0,返回较大的数,此数即为最大公约数,最小公倍数为两数之积除以最大公约数。* /

import .*;

public class lianxi06 {

public static void main(String[] args) {

int a ,b,m;

Scanner s = new Scanner();

t( "键入一个整数: ");

a = Int();

t( "再键入一个整数: ");

b = Int();

deff cd = new deff();

m = (a,b);

int n = a * b / m;

tln("最大公约数: " + m);

tln("最小公倍数: " + n);

}

}

class deff{

public int deff(int x, int y) {

int t;

if(x < y) {

t = x;

x = y;

y = t;

}

while(y != 0) {

if(x == y) return x;

else {

int k = x % y;

x = y;

y = k;

}

}

return x;

}

}

  【程序6】

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

import .*;

public class lianxi07 {

public static void main(String[] args) {

int digital = 0;

int character = 0;

int other = 0;

int blank = 0;

char[] ch = null;

Scanner sc = new Scanner();

String s = Line();

ch = arArray();

for(int i=0; i

if(ch >= '0' && ch <= '9') {

digital ++;

} else if((ch >= 'a' && ch <= 'z') || ch > 'A' && ch <= 'Z') {

character ++;

} else if(ch == ' ') {

blank ++;

} else {

other ++;

}

}

tln("数字个数: " + digital);

tln("英文字母个数: " + character);

tln("空格个数: " + blank);

tln("其他字符个数:" + other );

}

}