-2
該程序應該存儲2個團隊名稱和2個分數的輸入,在這樣做之後它應該輸出它們。輸出「null」的Java數組
數組只是印刷 「NULL [空] |空[空]」
import java.util.Scanner;
public class C3484209 {
public static void main(String[] args) {
String[] home_team_name = new String[100];
String[] away_team_name = new String[100];
String[] home_team_score = new String[100];
String[] away_team_score = new String[100];
Scanner keyboard = new Scanner(System.in);
String line = "";
while (!(line.equalsIgnoreCase("stop")))
{
System.out.println("Enter the teams that played and the score :");
System.out.println("(Please note that the standard format is Home team : Away Team : Home Score : Away Score)");
line = keyboard.nextLine();
String[] elements = line.split(": ");
for (int i = 0; i < elements.length;)
{
if ((int)i == 0)
{
home_team_name[i] = elements[0];
i++;
}
else if ((int)i == 1)
{
away_team_name[i] = elements[1];
i++;
}
else if ((int)i == 2)
{
home_team_score[i] = elements[2];
i++;
}
else if((int)i == 3)
{
away_team_score[i] = elements[3];
i++;
}
//System.out.print("Element " + (i+1) + " was : " + elements[i] + " | ");
System.out.println(home_team_name[i] + " [" + home_team_score[i] + "]" + " | " + away_team_name[i] +" [" + away_team_score[i] + "]");
}
}
//Output Command
keyboard.close();
}
}
這看起來像在介紹一個簡單的家庭作業編程類。你最好的選擇是在調試器中旋轉,以查看你的假設與實際情況無法匹配。相信JVM - 這些值爲空,因爲您沒有正確設置它們。在你的課程中可能爲時過早,但我建議創建一個Java對象來封裝這些值,並使用適當的toString方法來打印它們。你可以有一個更容易處理的對象列表。 – duffymo
不應該在'for循環'結尾的'System.out.println'語句超出for循環的範圍嗎?首先你需要在打印出來之前設置所有的值。我把'System.out.println'語句放在for循環之後,我嘗試編譯你的代碼,並且它工作正常。 – Yousaf