Except where otherwise noted, the contents of this document are Copyright 2012 Stuart Reges and Marty Stepp.
lab document created by Marty Stepp, Stuart Reges and Whitaker Brand
Goals for today:
Which of the following choices is the correct syntax for declaring/initializing an array of integers?
Which of the following choices is the correct syntax for quickly declaring/initializing an array of integers to store a particular list of values? We didn't get to this in lecture -- check the slides or chapter 7 in the book.
Fill in the array with the values that would be stored after the code executes:
int[] data = new int[8]; data[0] = 3; data[7] = -18; data[4] = 5; data[1] = data[0]; int x = data[4]; data[4] = 6; data[x] = data[0] * data[1];
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| value | 3 | 3 | 0 | 0 | 6 | 9 | 0 | -18 |
Fill in the array with the values that would be stored after the code executes:
int[] list = {2, 18, 6, -4, 5, 1};
for (int i = 0; i < list.length; i++) {
list[i] = list[i] + (list[i] / list[0]);
}
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| value | 3 | 24 | 8 | -5 | 6 | 1 |
public static type name(type[] name) { // pass array parameter
public static type[] name(parameters) { // return array
doubles, and returns a new array of rounded ints:
public static int[] roundAll(double[] realNums) {
int[] roundedNums = new int[realNums.length];
for (int i = 0; i < realNums.length; i++) {
roundedNums[i] = (int) Math.round(realNums[i]);
}
return roundedNums;
}
roundAll method from the previous slide:
import java.util.*; // to use Arrays
public class MyProgram {
public static void main(String[] args) {
double[] realNumbers = {5.5, 7.31, 8.09, -3.234234, 2.0, 0.0};
int[] roundedNumbers = roundAll(realNumbers);
System.out.println(Arrays.toString(roundedNumbers));
}
...
}
// Output: [5, 7, 8, -3, 2, 0]
Arrays class methods| Method name | Description |
|---|---|
Arrays.binarySearch(array, value)
|
returns index of value in a sorted array (< 0 if not found) |
Arrays.copyOf(array, length)
|
returns a new copy of an array |
Arrays.equals(array1, array2)
|
returns true if the two arrays contain same elements |
Arrays.fill(array, value)
|
sets every element to the given value |
Arrays.sort(array)
|
arranges the elements into sorted order |
Arrays.toString(array)
|
returns a string for the array, such as "[10, 30, -25, 17]" |
What values are stored in the array at the comment in main?
Note that the incrementAll method returns void, but does take an int[] parameter.
public class ArrayReference {
public static void main(String[] args) {
int[] nums = {2, 4, -1, 3};
incrementAll(nums);
// HERE!
}
public static void incrementAll(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i]++;
}
}
}
| index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| value | 3 | 5 | 0 | 4 |
Solve another reference mystery problem on PracticeIt!
Discuss it with your neighbor before submitting the answer and make sure you agree with each other's solution. There will be a problem of this type on the final!
Suppose that each array at right were passed as a parameter to
the mystery method below. Fill in the boxes with the array
contents after each method call.
public static void mystery(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] < a[i + 1]) {
a[i] = a[i + 1];
}
}
}
|
|
| 3 | 28 | 53 | 78 |
continued on the next slide...
System.out.print inside the if on line 23 and debug the program.
count,
and drop it on the main code window. This will show a view of its contents.
count array?
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| value | 4 | 4 | 0 | 10 | 0 | 4 | 4 | 0 |
continued on the next slide...
System.out.print is about to execute, then stops.)
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| value | 8 | 8 | 0 | 20 | 0 | 8 | 8 | 0 |
| index | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 |
|---|---|---|---|---|---|---|---|---|
| value | 0 | 0 | 0 | 8 | 8 | 0 | 0 | 0 |
1 2 3 4 5 6 7 8 9 10 |
// Returns the largest value in the given array.
public static int max(int data[10]) {
int max = 0;
for (int i = 0; i < data[].length(); i++) {
if (array[i] > max) {
max = array[i];
}
}
return max[];
}
|
The above attempted solution to Practice-It problem "max" has
7 problems. Open Practice-It from the link above, copy/paste this code
into it, and fix the errors. Complete the code so that it passes the test
cases.
[10] after parameter name; should
write [] (without length) after int
max at 0 won't work if the
array is all negative. Should initialize max variable to
be data[0] and start for loop at
index 1
[] after data here
() after length here
array should be data
array should be data
[] after max here
1 2 3 4 5 6 7 8 9 10 |
// Returns the largest value in the given array.
public static int max(int[] data) {
int max = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
|
PromptNumbers.java program from a previous exercise.
public class PromptNumbers2 {
public static void main(String[] args) {
int count = console.nextInt();
int[] nums = new int[count];
...
System.out.println("Your numbers in forward order:");
printForward(nums);
System.out.println("Your numbers in backward order:");
printBackward(nums);
}
// Prints the elements of the given array in forward order.
public static void printForward(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
// Prints the elements of the given array in backward order.
public static void printBackward(int[] a) {
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i]);
}
}
}
minGap
Write a method named minGap that accepts an integer array as a
parameter and returns the minimum 'gap' between adjacent values in the
array. The gap between two adjacent values in a array is defined as the
second value minus the first value. For example, suppose a variable
called array is an array of integers that stores the following
sequence of values:
int[] array = {1, 3, 6, 7, 12};
The first gap is 2 (3 - 1), the second gap is 3 (6 - 3), the third gap is 1
(7 - 6) and the fourth gap is 5 (12 - 7). Thus, the call
of minGap(array) should return 1 because that is
the smallest gap in the array. If you are passed an array with fewer than
2 elements, you should return 0.
Click on the check-mark above to try out your solution in Practice-it!
percentEven
Write a method named percentEven that accepts an array of
integers as a parameter and returns the percentage of even numbers in the
array as a real number. For example, if a variable named nums
refers to an array of the elements {6, 2, 9, 11, 3}, then the
call of percentEven(nums) should return 40.0. If
the array contains no even elements or no elements at all,
return 0.0.
Click on the check-mark above to try out your solution in Practice-it!
copyRange
Write a method named copyRange that takes as parameters two
arrays a1 and a2, two starting
indexes i1 and i2, and a length l,
and copies the first l elements of a1 starting at
index i1 into array a2 starting at
index i2.
For example, if the following arrays are declared:
int[] a1 = {10, 20, 30, 40, 50, 60};
int[] a2 = {91, 92, 93, 94, 95, 96};
copyRange(a1, a2, 0, 2, 3);
After the preceding call, the contents of a2 would
be {91, 92, 10, 20, 30, 96}. You may assume that the
parameters' values are valid, that the arrays are large enough to hold the
data, and so on.
equals
Write a method named equals that accepts two arrays of integers as parameters and returns true if they contain exactly the same elements in the same order, and false otherwise.
Note that the arrays might not be the same length; if the lengths differ, return false. Do not call Arrays.equals in your solution.
For example, if the following arrays are declared:
int[] a1 = {10, 20, 30, 40, 50, 60};
int[] a2 = {10, 20, 30, 40, 50, 60};
int[] a3 = {20, 3, 50, 10, 68};
The call equals(a1, a2) returns true but the call equals(a1, a3) returns false.
append
Write a method called append that accepts two integer arrays as parameters and that returns a new array that contains the result of appending the second array's values at the end of the first array.
You should solve this problem in Practice-It!
swapAll
Write a method named swapAll that accepts two arrays of
integers as parameters and swaps their entire contents. You may assume that
the arrays passed are not null and are the same length.
For example, if the following arrays are passed:
int[] a1 = {11, 42, -5, 27, 0, 89};
int[] a2 = {10, 20, 30, 40, 50, 60};
swapAll(a1, a2);
After the call, the arrays should store the following elements:
a1: {10, 20, 30, 40, 50, 60}
a2: {11, 42, -5, 27, 0, 89}
longestSortedSequence
Write a method called longestSortedSequence
that accepts an array of integers as a parameter and that returns the
length of the longest sorted (nondecreasing) sequence of integers in the
array.
You should solve this problem in Practice-It!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Counts the total lines and words in the given input scanner. public static void countWords(Scanner input) { Scanner input = new Scanner(new File("example.txt")); int lineCount = 0; int wordCount = 0; while (input.nextLine()) { String line = input.line(); // read one line lineCount++; while (line.next()) { // count tokens in line String word = lineScan.hasNext; wordCount++; } } } |
The above attempted solution to Practice-It problem
"countWords" has 5 errors.
Open Practice-It from the link above, copy/paste this code into it, and fix
the errors. Complete the code so that it passes the test cases.
Scanner for the
filenextLine should be hasNextLineline should be nextLineScanner to read the tokens of
each linehasNext should be next()println statements to print
line/word stats
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Counts the total lines and words in the given input scanner.
public static void countWords(Scanner input) {
|
coinFlip
Write a method named coinFlip that accepts
a Scanner for an input file of coin flips that are heads (H)
or tails (T). Consider each line to be a separate set of coin flips and
output the number and percentage of heads in that line. If it is more than
50%, print "You win!". Consider the following file:
H T H H T
T t t T h H
h
For the input above, your method should produce the following output:
3 heads (60.0%) You win! 2 heads (33.3%) 1 heads (100.0%) You win!
printDuplicates
Write a method printDuplicates that accepts a Scanner for an input file.
Examine each line for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively. For example the file:
hello how how are you you you you I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge one fish two fish red fish blue fish bow wow wow yippee yippee yo yippee yippee yay yay yay
leads to the following console output:
how*2 you*4 I*3 Jack's*2 smirking*5 wow*2 yippee*2 yippee*2 yay*3
mostCommonNames
Write a method mostCommonNames that accepts a Scanner for an input file with names on each line separated by spaces. Some names appear multiple times in a row. For example:
Benson Eric Eric Marty Kim Kim Kim Jenny Nancy Nancy Nancy Paul Paul Stuart Stuart Stuart Ethan Alyssa Alyssa Helene Jessica Jessica Jessica Jessica Jared Alisa Yuki Catriona Cody Coral Trent Kevin Ben Stefanie Kenneth
For each line, print the most commonly occurring name. If there's a tie, use the first name that had that many occurrences.
Most common: Kim Most common: Jessica Most common: Jared
Also return the total number of unique names in the whole file (e.g. 23 for the above input).
stripHtmlTags
Write a method stripHtmlTags that accepts a Scanner for an input file containing an HTML web page, then reads that file and prints the file's text with all HTML tags removed. A tag is any text between the character < and >. For example, consider the following text:
<html> <head> <title>My web page</title> </head> </html>
If a file containing these lines were passed to your program, your program should output the following:
My web page
If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.
You can view an exercise, type a solution, and submit it to see if you have solved it correctly.
Choose some problems from the book and try to solve them!