[英]Printing an array that already contains values
I'm experimenting with code, and I was wondering how would I go about printing an array that already contains values? 我正在尝试代码,我想知道如何打印已经包含值的数组? If I were to add something like "The temperatures of the week are: " and then print the list out to the user.
如果要添加诸如“一周的温度是:”之类的内容,然后将列表打印出给用户。 This is my code:
这是我的代码:
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]);
}
}
}
You can either explicitly loop through the array, or use the Arrays.toString method. 您可以显式遍历数组,也可以使用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();
or you could 或者你可以
System.out.println("The temperatures of the week are: " + Arrays.toString(arr));
You need to first import java.util.Arrays to use the Arrays class. 您需要首先导入java.util.Arrays才能使用Arrays类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.