I have nothing to do and implement a small game of guessing numbers. The purpose is to consolidate my basic knowledge and cultivate the fun of typing code.
First import the package into the class created in the project
(Video tutorial recommendation: java course)
import java.util.Scanner;//一个简单的文本扫描器,可以使用正则表达式解析原始类型和字符串。
Get a random number
double number=Math.random();//随机数取值范围[0.0~1.0] //如果想求出1~100之间的随机数 int number=(int)(Math.random()*100+1);
Execute while loop using while infinite loop (unknown the number of loops)
while(true){ Scanner sc=new Scanner(System.in);//创建键盘录入对象 System.out.println("请您输入一个数据:"); int guessNum=sc.nextInt();//提示并接收 if(guessNum>number){ System.out.println("您输入的数据大了!"); }else if(guessNum<number){ System.out.println("您输入的数据小了!"); }else if(guessNum=number){ System.out.println("恭喜您,猜中了!"); break;//结束循环!(中断,结束) } }
Execution result:
请输入一个数字: 56 输入数字过小! 请输入一个数字: 78 输入数字过小! 请输入一个数字: 89 输入数字过小! 请输入一个数字: 90 恭喜您,猜对了!
Related recommendations:Getting started with java
The above is the detailed content of Java implements word guessing game. For more information, please follow other related articles on the PHP Chinese website!