第二章程序基本概念
1.打印出100~1000范围内的所有“水仙花数”
代码如下
package www.zbq.com;
public class Test {
public static void main(String[] args) {
int a = 0;
int b = 0;
int c = 0;
int sum = 0;
for (int x = 100; x < 100; x++) {
a = x / 100;
b = (x / 10 % 10);
c = x - (a * 100 + b * 10);
sum = a * a * a + b * b * b + c * c * c;
if (sum == x) {
System.out.println(x);
}
}
}
}
2.通过代码完成两个整数内容的交换
代码如下
package www.zbq.com;
public class Test {
public static void main(String[] args) {
int a = 121;
int b = 212;
int c = 0;
c = a;
a = b;
b = c;
System.out.println(a);
System.out.println(b);
}
}
3.判断某数能否被3, 5,7同时整除
代码如下
package www.zbq.com;
public class Test {
public static void main(String[] args) {
int a = 105;
if ((a % 3 == 0) && (a % 5 == 0) && (a % 7 == 0)) {
System.out.println("可以被3,5,7同时整除");
} else {
System.out.println("不可以被3,5,7同时整除");
}
}
}
4.编写程序,分别利用while循环,do…while循环和for循环求出100~200的累加和
代码如下
while循环
package www.zbq.com;
public class Test {
public static void main(String[] args) {
int x = 100;
int sum = 0;
while (x < 201) {
sum += x;
x++;
}
System.out.println(sum);
}
}
do…while循环
package www.zbq.com;
public class Test {
public static void main(String[] args) {
int x = 100;
int sum = 0;
do {
sum += x;
x++;
} while (x < 201);
System.out.println(sum);
}
}
for循环
package www.zbq.com;
public class Test {
public static void main(String[] args) {
int sum = 0;
for (int x = 100; x < 201; x++) {
sum += x;
}
System.out.println(sum);
}
}