Objectives

Scanner · primitive arrays · counter-controlled loops

Demo Exercise

This step introduces a way to write and check your exercises on IntelliJ.

For each exercise, you should write the code in its own method and give it a similiar method header to this:

    public static void exercise_demo()

Note the use of the static modifier in the method header.

Demo Exercise

Perform these steps:

  • In IntelliJ, create a new Project called ArrayExercises.

  • Create a class in this Project called PrimitiveArrays

  • Write a method to read in 6 integers into an integer array and then print out the values to the screen.

Solution to the Demo Exercise

import java.util.*;

public class PrimitiveArrays {

    private static Scanner input = new Scanner (System.in);

    public static void main(String[] args) 
    {    
        exercise_demo();
    }

    public static void exercise_demo()
    {
        int numbers[] = new int[6];

        for (int i = 0; i < numbers.length ; i++)
        {
            System.out.print("Enter value : ");
            numbers[i] = input.nextInt();
        }

        for (int i = 0; i < numbers.length ; i++)
        {
            System.out.println("value " + (i+1)  + " is: " + numbers[i]);
        }
    }
}

Exercises

Using the same method naming system and use of static methods, attempt the following exercises.

In each case:

  • Add a method to the PrimitiveArrays class as written in the previous step.

  • declare the primitive array as needed locally in your method.

  • use the global Scanner object to read in data from the user.

  • call your writen method from the main class (and comment out calls to other methods).

Exercise 1

Write a method to read in 6 integers into an integer array and then print the values out backwards. Call this method exercise_1.

Exercise 2

Write a method to read in 10 values into an integer array. Then add one to each value in the array. Finally, print out the resultant values in the array. Call this method exercise_2.

Exercise 3

Write a method to read in 10 ‘wages’ into a ‘double’ array (i.e. an array where each element is a double, for instance 2.33). Finally print out these values. Call this method exercise_3.

Exercise 4

Write a method to Similar to above , i.e. read in 10 ‘wages’ into a ‘double’ array (i.e. an array where each element is a double, for instance 2.33). This time only print out any wages over 100. Call this exercise_4.

Exercise 5

Similar to above, i.e. Read in 10 ‘wages’ into a ‘double’ array (i.e. an array where each element is a double, for instance 2.33). Anyone who earns over 1000 will have a wage reduction of 10%. Make this reduction. Finally print out all the values. Call this method exercise_5.

Exercise 6

Write a method to read in 10 'wages' into a 'double' array as above. Calculate and print the average of the inputted wages. Call this method exercise_6.

Solution

The solution to these exercises is here.