简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM