对于构造函数,我要为用户分配每个变量的值。变量是:
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
对于构造函数,我从每个变量的用户那里获取一个值。我已经找到了行和列,但我怎么能处理为treasureLocations获取用户输入的地方,它只能是一个输入值(例如0,1,2 ......)? 请记住,我无法添加任何其他字段! 提前谢谢!
public TreasureMap(){
System.out.println("How many rows would you like to have? ");
rows = kbd.nextInt();
System.out.println("And how many columns would you like to have? ");
cols = kbd.nextInt();
System.out.println("Now enter the number of treasures you'd like to have: ");
treasureLocations[] = kbd.nextInt();
}
答案 0 :(得分:0)
treasureLocations[] = new Coord [kbd.nextInt()];
答案 1 :(得分:0)
在接受宝藏数量时声明数组。
public TreasureMap(){
System.out.println("How many rows would you like to have? ");
rows = kbd.nextInt();
System.out.println("And how many columns would you like to have? ");
cols = kbd.nextInt();
System.out.println("Now enter the number of treasures you'd like to have: ");
int[] treasureLocations = new int[kbd.nextInt()];
}
由于在接受所需元素数量之前已声明了数组,因此无法使用确切的元素数声明数组。
另一种解决方法是将该输入存储在另一个变量中,并循环后面的输入和输出序列,确切次数。