2013-12-20 118 views
-1
JButton nupp0 = new JButton(); // Teen nupu objektid, rida 54 
JButton nupp1 = new JButton(); 
JButton nupp2 = new JButton(); 
JButton nupp3 = new JButton(); 
JButton nupp4 = new JButton(); 
JButton nupp5 = new JButton(); 
JButton nupp6 = new JButton(); 
JButton nupp7 = new JButton(); 

public JButton nupud[] = { nupp0, nupp1, nupp2, nupp3, nupp4, nupp5, nupp6, nupp7 }; 

有人告訴我在for循環中創建這個代碼的方法,但我嘗試了很多方法,但我無法使它工作。有任何想法嗎?Java For Loop問題

這是我的2次嘗試:

for (int i =0 ; i < nupud.length ; i++) { 
    JButton nupud[i] = new JButton;  
} 

for (int i = 0 ; i < nupud.length ; i++) { 
    nupud[i] = new JButton(); 
} 
+1

我們都得到了循環的問題。此外,我們不知道你正在努力完成什麼。另外,**查看數組語法**。 –

+2

假設你已經初始化了數組,第二個片段看起來是正確的。你面臨的問題是什麼? – Mureinik

+0

你面臨什麼問題? – Deepak

回答

5

就新了數組第一:

JButton[] nupud = new JButton[8]; 
for (int i = 0 ; i < nupud.length; i++){ 
    nupud[i] = new JButton(); 
} 
+0

現在和「nupp」一樣嗎? – user3086917

+0

@ user3086917這個解決方案不再需要'nupp'變量,這將使用8個獨特的JButton來初始化數組(如果需要更多的話,可以更改該值) –

0

看起來像你之前的循環缺少這一點。

JButton[] nupud = new JButton[length]; 
0

我只是檢查我的日食工作:

package com.demo.swain; 

public class JButton { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     JButton nupp0 = new JButton(); // Teen nupu objektid, rida 54 
     JButton nupp1 = new JButton(); 
     JButton nupp2 = new JButton(); 
     JButton nupp3 = new JButton(); 
     JButton nupp4 = new JButton(); 
     JButton nupp5 = new JButton(); 
     JButton nupp6 = new JButton(); 
     JButton nupp7 = new JButton(); 

    JButton[] nupud = { nupp0, nupp1, nupp2, nupp3, nupp4, nupp5, nupp6, nupp7}; 
     for (int i =0 ; i < nupud.length ; i++) { 
      nupud[i] = new JButton(); 
        System.out.println(nupud[i]); 
     } 
    } 

} 

輸出:

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected]