我有這個應用程序,其中有一個數組元素4.我需要將每個單個房間對象添加到數組中,當用戶輸入時,他/她最多可以輸入4個對象。但是當我只輸入一個房間對象時,它顯示了該對象添加的數組中的所有元素。我可以知道爲什麼,有人可以幫忙嗎? 謝謝!爲什麼我的for循環同時添加一個對象?
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
class TestRoom {
public static void main(String [] args)
{
String[] roomsInHouse = new String[4];
int answer;
do{
String nameOfRoom = JOptionPane.showInputDialog(null, "Enter the name of the room");
String dimsOfRoom = JOptionPane.showInputDialog(null, "Enter the dimension of the room in feet L X W X H");
Scanner userInput = new Scanner(dimsOfRoom);
double l = userInput.nextDouble();
double w = userInput.nextDouble();
double h = userInput.nextDouble();
Room roomDetails = new Room(nameOfRoom, l, w, h);
String n = Double.toString(l);
String o = Double.toString(w);
String p = Double.toString(h);
for(int i = 0; i < roomsInHouse.length; i++)
{
roomsInHouse[i] = nameOfRoom + dimsOfRoom;
}
answer = JOptionPane.showConfirmDialog(null, "Input another room?", "Area/Volume calculator", JOptionPane.YES_NO_CANCEL_OPTION);
} while(answer == JOptionPane.YES_OPTION);
for(String j: roomsInHouse)
{
System.out.println(j);
}
}
}
好的我剛剛改變了我的編碼,並感謝你們的貢獻,我明白出了什麼問題。乾杯!
int counter = 0;
roomsInHouse[counter++] = nameOfRoom + dimsOfRoom;
answer = JOptionPane.showConfirmDialog(null, "Input another room?", "Area/Volume calculator", JOptionPane.YES_NO_CANCEL_OPTION);
} while(answer == JOptionPane.YES_OPTION && counter < 4);
「但是,當我只輸入一個房間對象時,它顯示了該對象添加的數組中的所有元素。」不正是嵌套的'for'循環正在做什麼? – dasblinkenlight
你確定你正在輸入房間的名字嗎?因爲我沒有在代碼中看到它 – gprathour