JavaSE:猜数字小游戏的实现源码

实现要求:

JavaSE:猜数字小游戏的实现源码_第1张图片

根据要求,代码实现如下:

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

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Random rand = new Random();
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入猜数范围:下限和上限");
        System.out.println("猜数范围下限:");
		int down = scan.nextInt();
        System.out.println("猜数范围上限:");
		int up = scan.nextInt();
		int key = rand.nextInt(up-down+1)+down;
		int num = 1;//猜数字的次数
		//System.out.println(key);
		while(true) {
			System.out.print("请输入您猜的数字->");
			int guess = scan.nextInt();   //要猜的数字
			if(guess == key) {
				System.out.println("第"+num+"次猜数为->"+guess+",恭喜你猜中!");
				break;
			}
			else if(guess > key) {
				System.out.println("第"+num+"次猜数"+guess+"大了!");
			}
			else {
				System.out.println("第"+num+"次猜数"+guess+"小了!");
			}
			num++;
		}
	}

}

你可能感兴趣的:(java,开发语言)