猜数游戏
最早接触是在学习C语言,跟着慕课网浙大翁凯老师学习的。
可能对于非科班的同学来说,一个猜数游戏没有什么,但也许只有计科的同学才能明白这一道猜数游戏中的奥秘:不一样的语言,同一个逻辑;每一次 写,不一样的收获
子曰: “ 温故而知新,可以为师矣。”
import java.util.Random;
import java.util.Scanner;
//引入了两个java自带封装好的函数(组件库)
public class 猜数游戏 {
public static void main(String[] args0){
//1.通过Random类中的nexInt(int n)方法 生成一个的随机数
int randomNumber = new Random().nextInt(10);
System.out.println("随机数已经生成");
//2.输入猜的数字
System.out.println("请输入您猜的数字");
Scanner sc= new Scanner(System.in);
//new 了个对象,平平无奇的定义
int enterNumber=sc.nextInt();
//3.定义一个循环实现判断,完善程序判断功能
while (enterNumber !=randomNumber){
//第一次猜错了
if(enterNumber > randomNumber){
//猜的数大了的情况
System.out.println(("对不起,您猜大了"));
}else {
//数猜小了
System.out.println("对不起,您猜小了");
}
//设置再次输入的数字,进行此次尝试
System.out.println("请再次输入您选择的数字");
enterNumber=sc.nextInt();
//定义好的函数,调用
}
//
System.out.println("恭喜你答对了!");
}
}
效果