我使用Random类生成从1到20的数字。然后,我将它添加到ArrayList中,但错误消息显示"无法对非静态方法进行静态引用nextInt(int)来自Random"类型。我该怎么办?以下是我的代码。
import java.util.ArrayList;
import java.util.Random;
public class ComputerChoose {
static ArrayList<Integer> computer_number = new ArrayList<>();
public static ArrayList<Integer> getTheNumber() {
for(int times=0; times<5; times++)
{
computer_number.add(Random.nextInt(20) + 1);
}
return computer_number;
}
}
答案 0 :(得分:2)
nextInt
不是静态方法。您必须创建Random
的实例,并将其称为实例方法:
import java.util.ArrayList;
import java.util.Random;
public class ComputerChoose {
static ArrayList<Integer> computer_number = new ArrayList<>();
public static ArrayList<Integer> getTheNumber() {
Random random = new Random();
for(int times=0; times<5; times++) {
computer_number.add(random.nextInt(20) + 1);
}
return computer_number;
}
}