2016-08-03 41 views
0

獲取其值假設我的代碼是我怎樣才能在一個循環中創建變量A1,A2,...,A10和Java中

public class GetValueInLoop{ 

    public static void main(String[] args) throws InterruptedException { 
     int a1=3; 
     int a2=4; 
     int a3=5; 
     int result; 

     for(int i=1; i<4;i++){ 
      result = a(i); 
      System.out.println("Value of a(i): "+result); 

      } 
     } 

我怎樣才能像輸出

Value of a1:3 
Value of a2:4 
Value of a3:5 

誰能幫我出 感謝

+8

使用數組... – Eran

+2

改變變量的陣列('INT [] A =新INT [4]; ')並使用'a [i-1]'而不是'a(i)'(因爲你從1循環到4,但是數組索引是基於0的,即從0到3)。 – Thomas

回答

0

你最好使用一個數組:

public class GetValueInLoop{ 

    public static void main(String[] args) throws InterruptedException { 
     int[] a= {3, 4, 5}; 

     for(int i=0; i<a.length;i++){ 
      System.out.println("Value of a(" + (i+1) + "): " + a[i]); 

      } 
    } 

} 
+0

謝謝你的回覆 – DoubtClear

0

可以使用這樣

public class Main { 
     public static void main(String... args) { 
      int a[]={3,4,5}; 
      int result; 
      for(int i=0; i<a.length;i++){ 
       result = a[i]; 
       System.out.println("Value of a(i): "+result); 

      } 
     } 

    } 

輸出:

Value of a(i): 3 
Value of a(i): 4 
Value of a(i): 5 
相關問題