Page 416 - Introduction to Programming with Java: A Problem Solving Approach
P. 416

                382 Chapter 10 Arrays and ArrayLists
name, that is, the name of the array you’re copying to. The fourth argument is the index of the destination
array’s first element to replace. The final argument is the total number of elements to copy.
10.6 Problem Solving with Array Case Studies
In this section, we present two array-based case studies. For each case study, we present a examples. problem and then examine its solution. The point of these case studies isn’t so much that you memorize the details. The point is that you get a feel for how to solve array-oriented problems. Then when you’re a programmer in the real world, you’ll have a “bag of tricks” that you can draw from. You’ll probably have to modify the case-study solutions to make them fit your specific real-world problems,
but that’s OK. You’ve got to earn your keep, after all.
Shifting Array-Element Values
Consider the hours array in Figure 10.6. The hours array contains the scheduled work hours for a person for a 31 day period of time. The first element (hours[0]) contains the scheduled work hours for the person for the current day. The last element (hours[30]) contains the scheduled work hours for the person for the day that’s 30 days in the future. At the beginning of each new day, the work hours need to shift to lower- index positions. For example, the hours[1] value needs to shift to the hours[0] element. That should make sense when you realize that when you’re going to a new day, you need to make what was the next day’s scheduled hours, hours[1], become the current day’s scheduled hours, hours[0].
       Learn by
               Apago PDF Enhancer
0 first day’s hours 1
2
30 last day’s hours Array that holds scheduled work hours for next 31 days
index hours
      4
  8
  0
    8
 Figure 10.6
Now let’s look at Java code that performs this shifting operation. We want to shift each hours element value to its adjacent lower-indexed element. In other words, we want to copy the second element’s value into the first element, copy the third element’s value into the second element, and so on. Then we want to assign a user-entered value to the last element. Here’s the code:
  for (int d=0; d<hours.length–1; d++)⎫ ⎪ ⎬ ⎪ ⎭
{
 }
hours[d] = hours[d+1];
System.out.print("Enter last day's scheduled hours: ");
hours[hours.length-1] = stdIn.nextInt();
To shift values to lower-index positions, you must start at the low-index end and work toward the other end.








































































   414   415   416   417   418