我正在尝试使用代码,我想知道如何打印已经包含值的数组?如果我要添加诸如“一周的温度是:”之类的东西,然后将列表打印给用户。 这是我的代码:
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 :(得分: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类。