In this part, we’re going to learn how to create and use arrays. Arrays are very similar to lists in Python except they have a fixed size and they’re homogeneous, meaning all elements have the same type.
Open the file Arrays.java
in your repository using Visual Studio Code. You can refer back to Lab 1 if you need a refresher of how to do so.
Inside main
, create a new array of int
s of length 15:
int[] arr = new int[15];
We can access the elements of the array as arr[0]
, arr[1]
,… Write a for
loop that prints out each element of the array:
for (int i = 0; i < 15; i++) {
// Replace this comment with code to print out arr[i] here
}
With your partner, try to predict what will be printed. Now, run your code and examine the output before moving on. Okay, having done that, you’ve surely noticed that it printed the same value 15 times. Now, change just the line
int[] arr = new int[15];
to
int[] arr = new int[10];
Discuss what will happen with your partner and then run your code to check.
This happened because we changed the size of the array, but did not change the bounds of the loop. And this is what happens when we try to access an element of our array that is outside the bounds of the array.
The real problem is we hard coded the length 15 in the for
loop. We shouldn’t do that. Fortunately, we can get the length of an array arr
by using arr.length
. Go ahead and change the bound of the for
loop to be i < arr.length
and rerun your code. Much better!
Next, let’s try reading some int
s from the user and storing them in an array. Recall from the last lab that we can use a Scanner
to read int
s using the nextInt()
method. We can read from the input by creating a new Scanner
and then calling nextInt()
for each integer we want:
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
Create such a scanner. (Remember to import java.util.Scanner
at the top of your file.) Ask the user how many numbers they want to enter. Read the integer by calling scanner.nextInt()
. Now use that integer as the size of our array rather than our hard coded value 10. Next, change the loop from printing out the values of arr[i]
to instead prompt the user to enter a number, read the number using scanner.nextInt()
and store it in the array at index i
. We can store a value x
into an array arr
at index i
by using
arr[i] = x;
Now, write another for
loop to print out all of the elements of the array in reverse order. Here’s an example run of the program:
How many numbers do you want to enter? 3
Enter an int: 10
Enter an int: 20
Enter an int: 30
30
20
10
Use the git commands add
, commit
and push
to save your changes to Arrays.java
before you move on to the next part of the warmup.