Java from Getting Started to Abandoning Chapter 4 (Random, Scanner to achieve simple and small games)

Today, I will share with you a wave of Random, Scanner's java learning and practice. Made a small game that is bigger than the computer.

First, we create a file named compare_game.java, and then add the following code.
The complete code is as follows:

import java.util.Random;
import java.util.Scanner;


/**
 * 这是一个与电脑比较数字大小的[0,100]小游戏
 * @author Mr.Pan_学狂
 * created time by 2021-2-27
 */


class compare_game{
    
    
	public static void main(String[] args){
    
    
		System.out.println("比大小游戏v1.0版");
		System.out.println();
		Scanner sc = new Scanner(System.in);//创建输入对象
		Random random = new Random();//创建一个随机数对象
		String yes = new String("是");//定义字符yes
		String no = new String("否");//定义字符no
		for(int i = 0;i < 20;i++) {
    
    //循环20次
			System.out.println("请输入数字:");
			int number1 = sc.nextInt();//人输入的数字
			int number2 = random.nextInt(101);//电脑生成的随机数
			if(number1 < 0 | number1 > 100) {
    
    //如果输入的数字大于100或者是小于0则出错
				System.out.println("输入的数字超出范围!!");
				break;
			}
			if(number1 > number2) {
    
    
				System.out.println("电脑生成的随机数是"+number2);
				//System.out.println("输入的数字是"+number1);
				System.out.println("你获胜了!!");
				System.out.println("是否继续游戏?");
				String want = sc.next();
				System.out.println();
				if(want.equals(yes)) {
    
    //判断输入的字符是否是"是"
					continue;
				}
				else if(want.equals(no)) {
    
    //判断输入的字符是否是"否"
					System.out.println("退出游戏!!");
					break;
				}
				else {
    
    
					System.out.println("输入错误!!");
					break;
				}
			}
			else if(number1 < number2) {
    
    
				System.out.println("电脑生成的随机数是"+number2);
				System.out.println("电脑获胜了!!");
				System.out.println("是否继续游戏?");
				String want = sc.next();
				System.out.println();
				if(want.equals(yes)) {
    
    //同理
					continue;
				}
				else if(want.equals(no)){
    
    //同理
					System.out.println("退出游戏!!");
					break;
				}
				else {
    
    
					System.out.println("输入错误!!");
					break;
				}
			}
			else {
    
    
				System.out.println("电脑生成的随机数是"+number2);
				System.out.println("平局!!");
				continue;
			}
			//System.out.println("生成的随机数是"+number2);
	}
		}
}

The results of the operation are as follows:
Insert picture description here
Insert picture description here
Finally, thank you all for coming to watch my article. There may be many improprieties in the article, and I hope to point out Hehaihan.

Guess you like

Origin blog.csdn.net/weixin_43408020/article/details/114178385