先从如何初始化单缸说起
//First you need a place to hold the value that the user inputs
float radius, height;
//Then you need an object that can read input from the user.
Scanner sc = new Scanner(System.in);
//Tell the user what you are expecting them to do
System.out.println("Enter radius: ");
//Now use the object to read in a value (You will need to convert it)
radius = sc.nextFloat();
//Tell the user what you are expecting them to do
System.out.println("Enter height: ");
//Now use the object to read in a value (You will need to convert it)
height = sc.nextFloat();
Cylinder cylinders = new Cylinder(radius, height); //creates the individual cylinders
现在你如何初始化一个圆柱体数组。数组与 for 循环密切相关。所以我们把上面的代码包装在一个 for 循环中,就像这样。
Cylinder[] cylinders = new Cylinder[3];
//Then you need an object that can read input from the user.
// No reason to create it multiple times so create it outside the loop.
Scanner sc = new Scanner(System.in);
for (int i = 0; i < cylinders.length; i++) {
//First you need a place to hold the value that the user inputs
float radius, height;
//Tell the user what you are expecting them to do
System.out.println("Enter radius for cylinder[" + i + "]: ");
//Now use the object to read in a value (You will need to convert it)
radius = sc.nextFloat();
//Tell the user what you are expecting them to do
System.out.println("Enter height for cylinder[" + i + "]: ");
//Now use the object to read in a value (You will need to convert it)
height = sc.nextFloat();
cylinders[i] = new Cylinder(radius, height); //creates the individual cylinders
}