[英]Printing an array that already contains values
我正在嘗試代碼,我想知道如何打印已經包含值的數組? 如果要添加諸如“一周的溫度是:”之類的內容,然后將列表打印出給用戶。 這是我的代碼:
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]);
}
}
}
您可以顯式遍歷數組,也可以使用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類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.