猜随机数

ava每日一练:编写程序随即生成一个1-100之间的随机数。程序提示用户输入一个数字,不停猜测,直到猜对为止
   最后输出猜测的数字,和猜测的次数。并且如果没有猜中要提示用户输入的值是大了还是小了。

   “一分耕耘,一分收获。”在自己的理想道路上,多动脑筋,不断的思考,不停地学习,四肢能勤,不断地“书读百遍”,就会“其义自现”。

package com.yirose.java8.string;
import java.util.Scanner;

public class guessingDemo {
    public static void main(String[] args) {
        int truth = (int) (Math.random() * 100) + 1;
        int count = 0;
        while (true) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入1-100其中的数字:");
            int guess = sc.nextInt(); // 读取整型输入
            if (guess == truth) {
                count++;
                System.out.println("你共猜了" + count + "次,恭喜你猜对了");
                break;
            } else if (guess > 100) {
                count++;
                System.out.println("sorry,你猜的数字大于100,请输入100以内整数");
            } else if (guess > truth) {
                count++;
                System.out.println("sorry,你猜的数字大了一点,请重新猜");
            } else if (guess < truth) {
                count++;
                System.out.println("sorry,你猜的数字小了一点,请重新猜");
            }
        }
    }
}
原文地址:https://www.cnblogs.com/pxuan/p/7048495.html