THINK FIRST·CODE LATER

← All labs

Indexes that cannot be trusted

Problem

SafeArray creates an array of 10 numbers in which values[i] is i × i + 1. It then reads words until the end of the input; each word is supposed to be an index. For each word it prints the element at that index — but the user may type anything, and the program must never crash:

  • Integer.parseInt(text) throws a NumberFormatException when the word is not a whole number;
  • values[index] throws an ArrayIndexOutOfBoundsException when the index is not between 0 and 9.

Catch each exception with its own catch block and count the answers given and refused. For the input

3 9 10 two -1 0 4.5

the program prints

values[3] = 10
values[9] = 82
Out of bounds: 10 (valid indexes are 0 to 9)
"two" is not a whole number
Out of bounds: -1 (valid indexes are 0 to 9)
values[0] = 1
"4.5" is not a whole number
Answered 3, refused 4 - and the program never crashed

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l16-4-data-1.txt

3 9 10 two -1 0 4.5
What your program must print for l16-4-data-1.txt
values[3] = 10
values[9] = 82
Out of bounds: 10 (valid indexes are 0 to 9)
"two" is not a whole number
Out of bounds: -1 (valid indexes are 0 to 9)
values[0] = 1
"4.5" is not a whole number
Answered 3, refused 4 - and the program never crashed

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l16-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content l16-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.