Sitemap

Saturday, July 16, 2016

Java: Arrays

package com.company;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * Created by Sonal_Chaudhary on 7/16/2016.
 */
public class TestScoreAverage {
    public static void main(String[] args) {
        final int NUMBER_OF_STUDENTS = 3;

        /**
         * The first statement declares a variable called numbers of the array type, with each element of type int. The
         * second statement allocates contiguous memory for holding 10 integers and assigns the memory address of the first
         * element to the variable numbers. The declaration and allocation can be done in the same statement like below:
         * int[] marks = new int[NUMBER_OF_STUDENTS];
         * Array literals provide a shorter and more readable syntax while initializing an array like below:
         * int[] marks = {15, 2, 9, 200, 18};
         */
        int[] marks;
        marks = new int[NUMBER_OF_STUDENTS];

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));


            for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
                System.out.print("Enter marks for student #" + (i + 1) + ": ");
                String str = reader.readLine();
                marks[i] = Integer.parseInt(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //The clone method copies all the elements of the array into a new array
        int[] marksCopy = marks.clone();

        int total = 0;

        /**
         * The for-each construct is very useful if you want to traverse all the elements of the array. Specifically,
         * it allows you to iterate over collections and arrays without using iterators or index variables. The for-each
         * has certain restrictions. It can be used for accessing the array elements but not for modifying them.
         * The 'm' specifies the type of variable and its name.
         * for (int m : marks) {
         *      System.out.println (m);
         * }
         */
        for (int m : marksCopy) {
            total += m;
        }

        System.out.println("Average Marks " + (float) total / NUMBER_OF_STUDENTS);
        System.out.println(Arrays.toString(marksCopy)); //To print the contents of an array
    }
}