int random = (int) (Math.random() * 10 + 1);//此代码随机生成[1,10]之间的数
Math.random是double浮点数类型,因为是用int类型接收,所以应把(Math.random() * 10 + 1)强转为int类型
import java.util.Scanner; public class Random { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请你猜一猜:"); Scanner sc = new Scanner(System.in); int random = (int) (Math.random() * 10 + 1); int i; for (i = 1;; i++) { int sum = sc.nextInt(); if (sum == random) { System.out.println("猜对了,是" + random); break; } } System.out.println("猜了" + i + "次"); } }