「程序應該首先詢問房間有多少房間,使用循環計算每個房間的矩形區域(SQF)。房間和財產的總SQF。「如何在for循環中更改之前顯示值
因此,我終於得到了我的代碼工作,除了我不能得到1件事: 問題的例子:說我進入2個房間,然後對於第一個房間,我把10×2這是一個面積20,那麼對於第二個房間我把8×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));
}
}
}
這是因爲你沒有「displayData」,直到循環結束。你只會看到最後的結果。只需在循環內移動該行即可。 – durbnpoisn
@durbnpoisn AHHH你真了不起。非常感謝。我一直在這個愚蠢的事情永遠。我擺脫了「displayData」中毫無意義的循環,並將「displayData」放在頂部的循環中。謝謝! –