Reputation: 85
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]);
}
}
}
Upvotes: 0
Views: 120
Reputation: 2188
You can either explicitly loop through the array, or use the Arrays.toString method.
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.
Upvotes: 1