1、求100以内的所有素数
public static void main(String[] args) {
int i, j;
for (i = 2; i <= 100; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0)
break;
}
if (j >= i) {// 也可以写成j==i
System.out.print(i + " ");
}
}
}
2、随机产生一个1-100之间的整数,看能几次猜中。要求:猜的次数不能超过7次,每次猜完之后都要提示“大了”或者“小了”。
public static void main(String[] args) {
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
// 随机产生一个1-100之间的整数
int num = (int) (Math.random() * 100 + 1);
System.out.println(num);
// 设置猜测的次数
int count = 1;
while (count <= 7) {
System.out.println("请输入你猜测的数字:");
int guess = sc.nextInt();
if (guess > num) {
System.out.println("大了");
count++;
} else if (guess < num) {
System.out.println("小了");
count++;
} else {
System.out.println("猜对了");
break;
}
}
if (count > 7) {
System.out.println("只能猜测7次,机会用完了");
} else {
System.out.println("猜了" + count + "次");
}
sc.close();
}
3、输出小写的a-z以及大写的在Z—A
A:65 Z:90 a:97 z:122
public static void main(String[] args) {
for (int i = 97; i <= 122; i++) {
char ch = (char) i;
System.out.print(ch + " ");
}
System.out.println();
for (int i = 65; i <= 90; i++) {
char ch = (char) i;
System.out.print(ch + " ");
}
}
4、输出20-80之间能被3整除的整数,每5个一行
public static void main(String[] args) {
int num = 20;
int count = 0;
while (num <= 80) {
if (num % 3 == 0) {
System.out.print(num + " ");
count++;
if (count % 5 == 0) {
System.out.println();
}
}
num++;
}
}
5、打印出1000-2000年中所有的闰年,并以每行四个数的形式输出
public static void main(String[] args) {
int year = 1000;
int count = 0;
while (year <= 2000) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
System.out.print(year + " ");
count++;
if (count % 4 == 0) {
System.out.println();
}
}
year++;
}
}
6、A、B、C、D分别为0——9之间的整数,求出满足AB+CD=DA条件的数。
例如:90+09=99
public static void main(String[] args) {
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 10; b++) {
for (int c = 0; c < 10; c++) {
for (int d = 0; d < 10; d++) {
if (10 * a + b + 10 * c + d == 10 * d + a) {
System.out.println(a + "" + b + "+" + c + "" + d + "=" + d + a);
}
}
}
}
}
}
7、输出九九乘法表
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 + "=" + (i * j) + "\t");
}
System.out.println();
}
}