关于Random和Int(Java)的问题

时间:2015-12-24 03:25:37

标签: java random

假设我生成1-10之间的随机数,我如何使用for循环中生成的随机数?有没有办法将随机转换为int?

public class CityTravelerApp {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    // TODO code application logic here

    Queue myQueue= new Queue(80);

    //a. Generate a random number called num between 1 and 10, inclusive. 
    Random number = new Random();
    System.out.println(number.nextInt(10)+1);


    for(int i =1;i<=number;i++){
        System.out.println("Enter the name of country #" + i);
        String name = input.next();
    }


    }

1 个答案:

答案 0 :(得分:2)

numberRandom Object,您无法循环使用它与int i进行比较,而是存储number.nextInt的结果到某个int变量并在for循环中使用该变量。基本上,您无法将intRandom进行比较,因为这两种类型都不兼容

Random number = new Random();
int limit = number.nextInt(10) + 1;

for(int i = 1; i <= limit; i++){
   ...
}