“程序应首先询问酒店有多少房间。使用循环计算每个房间的矩形区域(SQF)。显示每个房间的SQF和房产的总SQF。”
所以,我终于让我的代码工作了,除了我不能得到一件事: 问题的例子:假设我进入2个房间,然后对于第一个房间我放入10 x 2,这是20的区域,然后对于第二个房间我放8 x 2,这是16。 好吧当代码在最后显示信息时,它只显示16作为两个房间的区域,我假设这是因为这是计算的最后一个区域。 在最后它显示总面积为36所以我知道我接近正确的道路。但我不能为我的生活弄清楚这一点。
import javax.swing.JOptionPane;
public class PropertySF
{
public static void main(String[] args)
{
double length = 0, // The room's length
width = 0, // The room's width
area = 0; // The room's area
int numRoom; // for number of rooms
double roomSF = 0; // square footage for each room
double totalSF = 0; // Total square footage
// Get the amount of rooms
numRoom = getRooms();
// Get the rooms dimentions from the user.
for (double maxRoom = 1; maxRoom <= numRoom; maxRoom++)
{
length = getLength();
// Get the rooms's width from the user.
width = getWidth();
// Get the rooms's area.
area = getArea(length, width);
totalSF += area;
}
// Display the room data.
displayData(numRoom, totalSF, area);
System.exit(0);
}
public static int getRooms()
{
//See CL 5-10 Page 298
String input; //For input
//get input from user
input = JOptionPane.showInputDialog("Enter the number of rooms in the
the house: "); //Line 37
return Integer.parseInt(input); //Line 45- 48
}
/**
*The getLength prompts user for the length of the room
*@return value entered by user.
*/
public static double getLength()
{
//See CL 5-10 Page 298
String input; //For input
//get input from user
input = JOptionPane.showInputDialog("Enter the length of the room:");
return Double.parseDouble(input); //Line 45- 48
}
/**
*The getWidth prompts user for the Width of the room
*@return value entered by user.
*/
public static double getWidth()
{
//See CL 5-10 Page 298
String input; //For input
//get input from user
input = JOptionPane.showInputDialog("Enter the width of the room:");
return Double.parseDouble(input); //Line 45-48
}
/**
* The getArea method will calculate the room's area
* @param length the room's length
* @param with the room's width
* @return the area of the room
*/
public static double getArea(double length, double width)
{
return length * width;
}
/**
* The displayData method displays the rooms data.
*
*/
public static void displayData(double numRoom,
double totalSF,
double area)
{
for (double maxRoom = 1; maxRoom <= numRoom; maxRoom++)
{
JOptionPane.showMessageDialog(null,
String.format("The Square footage for room %f is %f,\n" +
"The total SQF is: %f \n", maxRoom, area,
totalSF));
}
}
}
答案 0 :(得分:0)
是的,area
只被传递到displayData函数一次,因此循环中只有一个值。一种可能的解决方案是传入一个区域数组,然后循环通过房间,但我认为更好的解决方案是在displayData中一次只显示一个房间(所以从displayData中删除循环,然后移动函数调用main中的循环)并将totalSF显示移动到另一个函数(如果你不想显示totalSF的运行总数)。
答案 1 :(得分:0)
可能的解决方案是将区域定义为数组或list(如果大小未知),将值存储在数组中并显示它。虽然有几种方法可以做到这一点。