如何将随机整数存储到 class 的实例中
How to store random integers into an instance of a class
我的任务是使用 10 个随机整数值(10 - 20) 作为它们的长度并将 10 个 Square 实例存储在 sqArray
中并打印出数组中所有元素的长度和面积。
这是我的正方形代码 class
public class Square {
private int length;
// Create a constructor that takes in len as parameter
public Square(int len){
length = len;
}
public int getLength(){
return length;
}
public double calculateArea(){
return length * length;
}
} //Square
这是我的主要代码 class
public class SquareUser {
public static void main(String[] args) {
//Create an instance of array sqArray.
Square[] sqArray = new Square [10];
for(int i = 0; i < sqArray.length; i++) {
sqArray[i] = (int) (Math.random()*10);
}
}
}
如您所见,我在 main class
中并没有真正做任何事情,因为我不知道这个问题在说什么。我有 2 个问题:
如果数据类型是对象,如何在for循环中生成一个随机整数?
"store the 10 Square instances in sqArray
"是什么意思?他们是要我将随机整数存储在 sqArray
?
中吗?
您只需生成 10 到 20 之间的随机整数并将其设置为创建的对象即可:
public class SquareUser {
public static void main(String[] args) {
//Create an instance of array sqArray.
Square[] sqArray = new Square [10];
for(int i = 0; i < sqArray.length; i++) {
int val = 10 + (int) (Math.random()*10);
sqArray[i] = new Square(val);
System.out.println("Length is "+val);
System.out.println("Area is "+sqArray[i].calculateArea());
}
}
}
你快到了。
- 替换
sqArray[i] = (int) (Math.random()*10);
有
sqArray[i] = new Square( 10 + Math.floor((int) (Math.random()*11)));
- 恰好有 10 个元素的
Square
个对象数组
我的任务是使用 10 个随机整数值(10 - 20) 作为它们的长度并将 10 个 Square 实例存储在 sqArray
中并打印出数组中所有元素的长度和面积。
这是我的正方形代码 class
public class Square {
private int length;
// Create a constructor that takes in len as parameter
public Square(int len){
length = len;
}
public int getLength(){
return length;
}
public double calculateArea(){
return length * length;
}
} //Square
这是我的主要代码 class
public class SquareUser {
public static void main(String[] args) {
//Create an instance of array sqArray.
Square[] sqArray = new Square [10];
for(int i = 0; i < sqArray.length; i++) {
sqArray[i] = (int) (Math.random()*10);
}
}
}
如您所见,我在 main class
中并没有真正做任何事情,因为我不知道这个问题在说什么。我有 2 个问题:
如果数据类型是对象,如何在for循环中生成一个随机整数?
"store the 10 Square instances in
sqArray
"是什么意思?他们是要我将随机整数存储在sqArray
? 中吗?
您只需生成 10 到 20 之间的随机整数并将其设置为创建的对象即可:
public class SquareUser {
public static void main(String[] args) {
//Create an instance of array sqArray.
Square[] sqArray = new Square [10];
for(int i = 0; i < sqArray.length; i++) {
int val = 10 + (int) (Math.random()*10);
sqArray[i] = new Square(val);
System.out.println("Length is "+val);
System.out.println("Area is "+sqArray[i].calculateArea());
}
}
}
你快到了。
- 替换
sqArray[i] = (int) (Math.random()*10);
有
sqArray[i] = new Square( 10 + Math.floor((int) (Math.random()*11)));
- 恰好有 10 个元素的
Square
个对象数组