通过random函数实现java中随机数生成,不断循环猜测随机数直到正确结果。
代码如下:
package cn.itcast.demo1; import java.util.Random; import java.util.Scanner; public class random { public static void main(String[] args) { Random random = new Random(); int c = random.nextInt(20); int r = c+500; System.out.println(r); Scanner sc = new Scanner(System.in); while (true) { int a = sc.nextInt(); if (a>r) System.out.println("选则数过大"); if (a<r) System.out.println("选择数过小"); if (a==r) break; } System.out.println("选择数正确"); } }