1、打印所有水仙花数:
“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。
例如:153是一个“水仙花数”,因为153=1的三次方+5的三次方+3的三次方。
分析:三位数x,取百位的数字直接“x/100”,取十位则“x/10%10”,个位则直接“x%10”。
代码如下:
/**
* @author Hui
*/
public class GetNumb {
public static void main(String[] args) {
// a代表百位,b代表十位,c代表个位。
int a,b,c;
for (int i = 100;i < 1000;i++){
a = i/100;
b = i/10%10;
c = i%10;
if (a*a*a+b*b*b+c*c*c == i){
System.out.println(i);
}
}
}
}
2、打印九九乘法表:
使用for循环嵌套,打印九九乘法表。
/**
* @author Hui
*/
public class JiuJiu {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
for (int j = 1; j < 10; j++) {
if (i >= j){
System.out.print(j+"*"+i+"="+(i*j)+" ");
}
}
System.out.println();
}
}
}
3、猜数字游戏:
输入一个数字,然后进行猜数字,猜大了或猜小了会有提示,直到猜对才完成,跳出循环。
import java.util.Scanner;
/**
* @author Hui
*/
public class GuessNumb {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个数字:");
int numb = scanner.nextInt();
System.out.println("你猜一下这个数字是几?");
int guessNumb = -1;
while (true){
guessNumb = scanner.nextInt();
if (guessNumb == numb){
System.out.println("你猜对了!数字是:" + numb);
break;
}else if (guessNumb < numb){
System.out.println("你猜的数字小了!");
continue;
}
System.out.println("你猜的数字大了!");
}
}
}