Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Instructions: Download LabArraysClass.java Add an import statement that imports

ID: 3766575 • Letter: I

Question

Instructions:

Download LabArraysClass.java

Add an import statement that imports the package java.util.Arrays

Use the Arrays class members from the handout to complete the instructions.

Produce a labeled output as described below

You searched for number 9 twice and you received different results. Why?

Hint: check out the description of the method binarySearch in the Java documentation http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

Find out the reason and print it in the last line

Expected output:

iArray1: [6, 12, 3, 9]

iArray2: [7, 7, 7, 7, 7]

9 in iArray1: -2

iArray1 sorted: [3, 6, 9, 12]

9 in iArray1: 2

iArray3: [3, 6, 9]

iArray3 equals [3, 6, 9]: true

Reason: . . .

Explanation / Answer

import java.util.Arrays;

public class LabArraysClass

{

public static void main(String[] args)

{

int[] iArray1 = {6, 12, 3, 9};

int[] iArray2 = new int[5];

  

// fill iArray2 with 7

for (int i = 0; i < iArray2.length; i++) {

                   iArray2[i] = 7;

               }

  

// print iArray1 and iArray2 (toString)

System.out.println("iArray1: "+Arrays.toString(iArray1));

System.out.println("iArray2: "+Arrays.toString(iArray2));

  

// search for number 9 in iArray1 and print the value returned:

for (int i=0; i<iArray1.length; i++) {

                   if (iArray1[i] == 9) {

                       System.out.println("9 in iArray1: "+ i);

                       break;

                   }

               }

// sort iArray1 and print it

Arrays.sort(iArray1);

System.out.println("iArray1 sorted: "+Arrays.toString(iArray1));

// search for number 9 in iArray1 and print the value returned:

for (int i=0; i<iArray1.length; i++) {

                   if (iArray1[i] == 9) {

                       System.out.println("9 in iArray1: "+ i);

                       break;

                   }

               }

  

// create iArray3 and assign it the first 3 elements of iArray1; print it

int[] iArray3 = new int[3];

for (int i = 0; i < iArray3.length; i++) {

                   iArray3[i] = iArray1[i];

               }

System.out.println("iArray3: "+Arrays.toString(iArray3));

  

// test equality of new int[] {3, 6, 9} and iArray3; print result

int[] temp = new int[] {3, 6, 9};

int flag=0;

for(int i=0; i<temp.length; i++) {

   if (temp[i] != iArray3[i]) {

                       flag=1;

                       break;

                   }

}

if (flag==0) {

                   System.out.println("iArray3 equals [3, 6, 9]: true");

               }

}

}