1、 打印出100~1000範圍內的所有 “水仙花數”。所謂“水仙花數”是指一個三位數,其各位數字立方和等於該數本身。例如:153是一個“水仙花數”,153= 1^3 + 5^3 + 3^3。
public class Test03 {
public static void main(String[] args) {
int i, j, k;
for (int x = 100; x < 1000; x++) {
i = x / 100; // 百位數
j = (x / 10) % 10; // 十位數
k = x % 10; // 個位數
if (x == i * i * i + j * j * j + k * k * k) {
System.out.print(x + "、");
}
}
}
}
2、將兩個整數的內容進行互換。
方法一:使用中間變量
public class Test04 {
public static void main(String[] args) {
int x = 10;
int y = 20;
int temp = x;
x = y;
y = temp;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
方法二:利用數學計算完成
public class Test05 {
public static void main(String[] args) {
int x = 10;
int y = 20;
x += y ;
y = x - y;
x = x - y ;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
3、 判斷某個數能否被3,5,7同時整除。
public class Test06 {
public static void main(String[] args) {
int data = 105;
if (data % 3 == 0 && data % 5 == 0 && data % 7 == 0) {
System.out.println(data + "可以同時被3、5、7整除。");
} else {
System.out.println(data + "不可以同時被3、5、7整除。");
}
}
}
4、 用while循環、do…while循環和for循環求出100~200累加的和。
4.1 使用while循環
public class Test07 {
public static void main(String[] args) {
int sum = 0;
int x = 100;
while (x <= 200) {
sum += x;
x++;
}
System.out.println("累加結果:" + sum);
}
}
4.2 使用do…while循環
public class Test08 {
public static void main(String[] args) {
int sum = 0;
int x = 100;
do {
sum += x;
x++;
} while (x <= 200);
System.out.println("累加結果:" + sum);
}
}
4.3 使用for循環
public class Test09 {
public static void main(String[] args) {
int sum = 0;
for (int x = 100; x <= 200; x++) {
sum += x;
}
System.out.println("累加結果:" + sum);
}
}