Home > Java > Javagetting Started > body text

Java implements word guessing game

王林
Release: 2020-10-29 15:19:00
forward
2629 people have browsed it

Java implements word guessing game

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;//一个简单的文本扫描器,可以使用正则表达式解析原始类型和字符串。
Copy after login

Get a random number

double number=Math.random();//随机数取值范围[0.0~1.0]
//如果想求出1~100之间的随机数
int number=(int)(Math.random()*100+1);
Copy after login

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;//结束循环!(中断,结束)
		}
}
Copy after login

Execution result:

请输入一个数字:
56
输入数字过小!
请输入一个数字:
78
输入数字过小!
请输入一个数字:
89
输入数字过小!
请输入一个数字:
90
恭喜您,猜对了!
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template