2014-11-14 20 views
0

我正在試驗代碼,我想知道如何才能打印已包含值的數組?如果我要添加諸如「一週的溫度是:」然後將列表打印出來給用戶。 這是我的代碼:正在打印已包含值的數組

public static void main(String[] args) { 



    Scanner keyboard=new Scanner(System.in); 
    System.out.println("How many temperatures?"); 
    int size=keyboard.nextInt(); 
    int temp[]=new int[size]; 
    System.out.println("Please enter "+temp.length+" temperatures"); 
    double sum=0; 
    for(int i=0;i<temp.length;i++){ 
     temp[i]=keyboard.nextInt(); 
     sum=sum+temp[i]; 
    } 
    double average=sum/temp.length; 
    System.out.println("The average temperature is: "+average); 

    for(int i=0;i<temp.length;i++){ 

     if (temp[i]>average){ 
      System.out.println("Above average: "+temp[i]); 
     } 
     else if(temp[i]<average){ 
      System.out.println("Below average: "+temp[i]); 
     } 
     else if(temp[i]==average){ 
      System.out.println("Equal to average "+temp[i]); 
     } 

    } 
} 
+0

現在有什麼確切的問題? :) – Muhammad

+0

我不知道如何以單獨輸入的值彼此排列的方式打印數組 –

+0

現在問題已解決,因爲@turingcomplete回答了您的問題? :) – Muhammad

回答

1

您可以通過數組明確循環,或使用Arrays.toString方法。

int [] arr = {1, 2, 3, 4, 5}; 
System.out.print("The temperatures of the week are: "); 
for(int i = 0; i < arr.length; i++) 
    System.out.print(arr[i]+" "); 
System.out.println(); 

,或者你可以

System.out.println("The temperatures of the week are: " + Arrays.toString(arr)); 

您需要先進口java.util.Arrays中使用Arrays類。

+0

謝謝!它的工作:) –

+0

我沒有導入數組類,我只是使用了一個for循環,但它給了我想要的輸出 –

+0

兩者都將打印數組,唯一的區別是,Arrays.toString將打印數組方括號[1,2,3,4]。 – turingcomplete