Dana Vrajitoru
C101/I210 Computer Programming

C101/I210 Lab 11

Date: Wednesday, April 15, 2020.
Due date: Wednesday, April 22, 2020.

Objective: To work with arrays in Java.

Ex. 1. Array Methods

In this project we will write a few methods manipulating arrays.

Create a Java project in Eclipse and call it lab11. Create a class in this project called ArrayMethods and containing the main method. Write your name, course, semester, and homework number at the top as a comment.

a. Scanner

Add the code for the definition of a scanner, but make it a static class attribute instead of a variable in the main. The slides contain an example of how to do this.

b. Input and Output

Copy the methods discussed in the lecture to input and output an array.

static void printArray(float[] a) {
    for (int i = 0; i < a.length; i++)
        System.out.println(" " + a[i]);
    System.out.println();
}
static float[] inputArray1() {
    float[] a;
    System.out.println("Enter the size");
    int size = scan.nextInt();
    a = new float[size];
    System.out.println("Enter the elements of the array");
    for (int i = 0; i < size; i++)
        a[i] = scan.nextFloat();
    return a;
}

Modify them so that the arrays contain integers instead of floats.

c. Sum and Minimum

Copy the methods sumArray and findMin discussed in the lecture.

static float sumArray(float[] numbers) {
    float sum = 0.0f;
    for (int i = 0; i < numbers.length; i++)
        sum = sum + numbers[i];
    return sum;
}
static float findMin(float[] a) {
    float min = a[0];
    for (int i = 1; i < a.length; i++)
        if (a[i] < min)
            min = a[i];
    return min;
} 

Modify them so that the arrays contain integers instead of floats.

d. Interface Menu

Let's write an interface menu in the main that allows the user to choose which method we want to call.

Declare a boolean variable quit initialized as false, and a variable answer of type String. Declare an integer array.

Then use a do loop while quit is false. In the loop, output a message giving the user the choices: "I" for input, "O" for output, "M" for finding the minimum, and "S" for the sum. Then input the answer using scan.next().

After that, use a switch statement based on the answer and call the appropriate function in each case.

Run the program to make sure everything works correctly.

Turn in:

Upload ArrayMethods.java to Canvas in Assignments - Homework 11, or wait until you have completed the homework to upload both files at the same time.