【发布时间】:2016-03-01 21:49:13
【问题描述】:
“程序应该首先询问房产有多少房间。使用循环计算每个房间的矩形面积 (SQF)。显示每个房间的 SQF 和房产的总 SQF。”
所以,我终于让我的代码工作了,除了我无法得到 1 件事: 问题示例:假设我进入 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));
}
}
}
【问题讨论】:
-
这是因为在循环结束之前您不会“显示数据”。您只会看到最后的结果。只需将该行移到循环内即可。
-
@durbnpoisn 啊哈你太棒了。太感谢了。我一直在做这个愚蠢的事情。我摆脱了“displayData”中无意义的循环,只是将“displayData”放在循环的顶部。谢谢!
标签: java loops for-loop output