本章任务使用循环语句
任务一:打印九九乘法表
(一)编程实现
- 首先我们在
net.jia.t05
包里创建Task05
类
- 然后再编写程序
- 最后运行程序,查看结果
(二)知识讲解
1、双重循环语法格式
for(初始化表达式; 循环条件; 操作表达式) {
...
for(初始化表达式; 循环条件; 操作表达式) {
执行语句
...
}
...
}
(三)拓展练习
任务一、打印字符等腰三角形
- 让用户输入行数,比如10行,就打印10行等腰三角形
任务二、猜数小游戏
- 游戏规则:程序产生一个[1, 100]之间的随机整数,用户输入整数进行猜测,如果猜对了,就结束游戏;如果猜错了,程序会提示你是猜高了还是猜低了,然后让你继续输入整数进行猜测
(一)编程实现
- 在
net.jia.p02.t06
包里创建Task06
类
- 接下来编写程序实现
package net.jia.p02.t06;
import java.util.Random;
import java.util.Scanner;
/**
* 功能: 猜数小游戏
* 作者:贾慧琳
* 日期:2022年04月14日
*/
public class Task06 {
public static void main(String[] args) {
// 声明部分
int target,x;
Scanner sc= new Scanner(System.in);
// 产生猜测目标
Random random = new Random();
target = random.nextInt(100);
// 用户输入猜测的数
System.out.print("输入你猜测的整数:");
x = sc.nextInt();
// 判断用户是否猜测正确
while (x != target) {
if (x > target) {
System.out.println("朋友,你猜高了,继续猜吧~");
} else {
System.out.println("朋友,你猜低了,继续猜吧~");
}
// 用户输入猜测的数
System.out.print("输入你猜测的整数:");
x = sc.nextInt();
}
System.out.println("恭喜,你猜对了,游戏结束!");
}
}
- 最后运行程序,查看结果
- 采用二分法来猜测
- 在net.jia.p02.t06包里创建Task06_类
- 编写程序实现
package net.jia.p02.t06;
import java.util.Random;
import java.util.Scanner;
/**
* 功能:
* 作者:贾慧琳
* 日期:2022年04月14日
*/
public class Task06_ {
public static void main(String[] args) {
// 声明部分
int target,x;
Scanner sc= new Scanner(System.in);
// 产生猜测目标
Random random = new Random();
target = random.nextInt(100);
while (true) {
// 用户输入猜测的数
System.out.print("输入一个[1,100]的整数:");
x = sc.nextInt();
// 判断用户是否猜测正确
if (x > target) {
System.out.println("朋友,你猜高了,继续猜吧~");
} else if (x < target) {
System.out.println("朋友,你猜低了,继续猜吧~");
} else {
break; // 猜中了,跳出循环
}
}
System.out.println("恭喜,你猜对了,游戏结束!");
}
}
- 运行程序,查看结果