Skip to main content\(\newcommand{\N}{\mathbb N} \newcommand{\Z}{\mathbb Z} \newcommand{\Q}{\mathbb Q} \newcommand{\R}{\mathbb R}
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 8.2 Starter Level
Wrapper Classes
Objectives
Subsection 8.2.1 Overview
The Java program CourseNumbersArray manages a list of course numbers that a student is registered in. It performs the following tasks:
Initializes an integer array, registeredCourses
, with a set of course numbers: 1010, 1020, 2080, 2140, 2150, 2160
To add a new course, it copies the elements from registeredCourses
into a new, larger array, updatedCourses
, and adds the course to this new array
Prints the contents of updatedCourses
, the array that contains the newly-added course
Checks if updatedCourses
contains a specific course number
public class CourseNumbersArray {
public static void main(String[] args) {
int[] registeredCourses = {1010, 1020, 2080, 2140, 2150, 2160};
System.out.print("Originally registered for: ");
for(int course : registeredCourses){
System.out.print(course + ", ");
}
int[] updatedCourses = new int [registeredCourses.length + 1];
System.arraycopy(registeredCourses, 0, updatedCourses, 0, registeredCourses.length);
updatedCourses[registeredCourses.length] = 2280;
System.out.print("\nUpdated courses: ");
for(int course : updatedCourses){
System.out.print(course + ", ");
}
int courseCode = 2140;
boolean found = false;
for(int course : updatedCourses){
if(course == courseCode){
found = true;
}
}
if(found){
System.out.println("\nYou are registered for " + courseCode);
}
else{
System.out.println("You are not registered for " + courseCode);
}
}
}
Subsection 8.2.2 Instructions
Convert the existing program that uses an int[]
to use an ArrayList
of Integer
instead.
Hint.
.contains()
should simplify the search for a specific course.
The expected output is:
Originally registered for: 1010, 1020, 2080, 2140, 2150, 2160,
Updated courses: 1010, 1020, 2080, 2140, 2150, 2160, 2280,
You are registered for 2140
You have attempted
of
activities on this page.