Question

Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

Our 1st new array operation/method is remove. Implement as follows:

public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2: However, if indexOf() brought back -1 then there is no such key in the array to remove so you should just return false right here 3: otherwise (i.e. it was found) copy all the initialized elements above that index down one place to the left. Don't copy any cell at count or higher. Thse are garbage cells. Use a -for- or -while- loop to shift the block of cells down. 4: return true }

It is critical that you only copy initialized values down one slot to the left. Do not copy uninitialized cells. This means that the highest element you would ever copy to the left would be the element at count-1 since count-1 is the index of the last initialized element in any array.

Also, the caller (main) will decrement the count when it is sees a true value come back from remove. You cannot decrement the count inside the remove method since you only have access to a local copy of it. Even if you decrement your local copy of count in remove - it would not change the value of the count variable in main. They are two separate variables stored in two separate methods. This is why your remove method has to return a true/false so the caller (main) knows whether the remove attempt succeeded, and thus knows whether to decrement the counter in main or not.

Our 2nd array operation/method is upSize. Implement as follows:

public static int[] upSize( int[] fullArr ) { 1: Use the .length of the incoming array which is filled up and define a new array (call it biggerArr) and give it a length of 2 X the incoming full array. 2: Use a for loop to copy all the elements from the filled up array to the biggerArr ** understand why we did not pass in a count. The incoming array is full to capacity thus .length is the count. 3: return the reference to the bigger array. Main will assign that reference into the array reference in main thus swapping in a bigger array to replace the filled up one. }

This upSize operation only requires three statements. An array definition, a loop, a return statement. The loop will be a couple lines of code but the other two are just one-liners. If you find yourself writing more code that this you are probably making a mistake.

P3Input.txt || 13 8 15 11 18 19 20 17 5 7 14 9 2 12 4 3 ||

import java.util.*;
import java.io.*;

public class Project3
{

   static final int NOT_FOUND = -1;

   public static void main(String[] args) throws Exception
   {
       // LOAD ARRAY FROM TEXT FILE

       if (args.length == 0) // USER FORGOT TO PUT THE INPUT FILENAME ON COMMAND LINE
       {
           System.out.println("Looks like you forgot to put an input file name on the command line!\n"
                               + " like this => java Project3 P3input.txt\n");
           System.exit(0);
       }
       final int INITIAL_CAPACITY = 1; // WE WILL MOST DEFINTILEY TEST YOUR PROGRAM ON A FILE WITH MORE THAN 1

       int[] arr = new int[INITIAL_CAPACITY];
       int arrCount = 0; // ACTUAL NUMBER OF INTS WE PUT INTO ARRAY NOT ALWAYS .length
       Scanner infile = new Scanner(new File(args[0])); // args[0] = FILENAME YOU PUT ON CMD LINE
       while (infile.hasNextInt()) // i.e. AS LONG THE NEXT TOKEN IN THE FILE IS AN INT
       {
           if ( arrCount == arr.length ) // UH OH! THE ARRAY IS FULL! WHAT CAN WE DO?
           {   arr = upSize( arr ); //    WE ASSIGN INTO arr A REF TO A NEW ARRAY THAT IS 2 X AS BIG
               System.out.println("JUST DID UPSIZE: arr.length=" + arr.length + " arrCount=" + arrCount);
               System.out.print( "arr: ");
               printArray(arr, arrCount);
           }
           // AND NOW EITHER WAY - arr POINTS TO AN ARR THAT HAS SOME EMPTY SPACE FOR A NEW ELEMENT
           arr[arrCount++] = infile.nextInt(); // 2 THINGS AT ONCE. APPEND ELEMENT & INCR COUNTER
       }
       infile.close(); // IF YOU FORGET TO DO THIS JAVA DOES IT FOR YOU

       // print THE ARRAY ONTO SINGLE LINE.
       System.out.println("arr.length=" + arr.length + " arrCount=" + arrCount);
       System.out.print( "arr: ");
       printArray(arr, arrCount);

       //    REMOVE ALL KEYS FROM THE ARRAY
      
       for ( int key = 0 ; key <= 20 ; ++key )
       {
           if ( ! remove( arr, arrCount, key) ) // i.e. IF REMOVE RETURNED FALSE
           {
               System.out.print("removal of " + key + " failed. ");
           }
           else
           {
               System.out.print("removal of " + key + " succeeded. ");
               --arrCount; // MUST DECREMENT COUNT TO REFLECT ELEMENT WAS REMOVED
           }
           System.out.print("Now arr.length=" + arr.length + " arrCount=" + arrCount);
           System.out.print( " arr: ");
           printArray(arr, arrCount);
       }
      
   } // END MAIN

   static void printArray(int[] arr, int count)
   {
       for (int i = 0; i < count; ++i)
       {
           System.out.print(arr[i] + " ");
       }
       System.out.println();
   }

   // ####################################################################################
   // Y O U M U S T F I L L I N T H E S E M E T H O D S B E L O W
   // ####################################################################################

   // YOU MAY ASSUME THE incoming REF TO INT ARRAY IS NOT NULL
   public static boolean remove( int[] arr, int count, int key )
   {
       return false; // JUST TO MAKE IT COMPILE. REPLACE WITH YOUR CODE
   }
  
   public static int[] upSize( int[] fullArr )
   {
       return null; // JUST TO MAKE IT COMPILE. REPLACE WITH YOUR CODE
   }  
  
   // COPY IT FROM YOUR LAB#3 SOLUTION. USE IT IN REMOVE
   static int indexOf( int[] a, int count, int key )
   {
       return NOT_FOUND; //REPLACE WITH YOUR SOLUTION CODE FROM LAB#3
   }
} // END CLASS

0 0
Add a comment Improve this question Transcribed image text
Answer #1


import java.io.File;
import java.util.Scanner;

public class Project3 {

   static final int NOT_FOUND = -1;
   public static void main(String[] args) throws Exception
   {
       // LOAD ARRAY FROM TEXT FILE

   if (args.length == 0) // USER FORGOT TO PUT THE INPUT FILENAME ON COMMAND LINE
   {
   System.out.println("Looks like you forgot to put an input file name on the command line!\n"
   + " like this => java Project3 P3input.txt\n");
   System.exit(0);
   }
   final int INITIAL_CAPACITY = 1; // WE WILL MOST DEFINTILEY TEST YOUR PROGRAM ON A FILE WITH MORE THAN 1

   int[] arr = new int[INITIAL_CAPACITY];
   int arrCount = 0; // ACTUAL NUMBER OF INTS WE PUT INTO ARRAY NOT ALWAYS .length
   Scanner infile = new Scanner(new File(args[0])); // args[0] = FILENAME YOU PUT ON CMD LINE
   while (infile.hasNextInt()) // i.e. AS LONG THE NEXT TOKEN IN THE FILE IS AN INT
   {
   if ( arrCount == arr.length ) // UH OH! THE ARRAY IS FULL! WHAT CAN WE DO?
   { arr = upSize( arr ); // WE ASSIGN INTO arr A REF TO A NEW ARRAY THAT IS 2 X AS BIG
   System.out.println("JUST DID UPSIZE: arr.length=" + arr.length + " arrCount=" + arrCount);
   System.out.print( "arr: ");
   printArray(arr, arrCount);
   }
   // AND NOW EITHER WAY - arr POINTS TO AN ARR THAT HAS SOME EMPTY SPACE FOR A NEW ELEMENT
   arr[arrCount++] = infile.nextInt(); // 2 THINGS AT ONCE. APPEND ELEMENT & INCR COUNTER
   }
   infile.close(); // IF YOU FORGET TO DO THIS JAVA DOES IT FOR YOU

   // print THE ARRAY ONTO SINGLE LINE.
   System.out.println("arr.length=" + arr.length + " arrCount=" + arrCount);
   System.out.print( "arr: ");
   printArray(arr, arrCount);

   // REMOVE ALL KEYS FROM THE ARRAY
  
   for ( int key = 0 ; key <= 20 ; ++key )
   {
   if ( ! remove( arr, arrCount, key) ) // i.e. IF REMOVE RETURNED FALSE
   {
   System.out.print("removal of " + key + " failed. ");
   }
   else
   {
   System.out.print("removal of " + key + " succeeded. ");
   --arrCount; // MUST DECREMENT COUNT TO REFLECT ELEMENT WAS REMOVED
   }
   System.out.print("Now arr.length=" + arr.length + " arrCount=" + arrCount);
   System.out.print( " arr: ");
   printArray(arr, arrCount);
   }
  
   } // END MAIN

   static void printArray(int[] arr, int count)
   {
   for (int i = 0; i < count; ++i)
   {
   System.out.print(arr[i] + " ");
   }
   System.out.println();
   }

   // ####################################################################################
   // Y O U M U S T F I L L I N T H E S E M E T H O D S B E L O W
   // ####################################################################################

   // YOU MAY ASSUME THE incoming REF TO INT ARRAY IS NOT NULL
   public static boolean remove( int[] arr, int count, int key )
   {
   int idx = indexOf(arr,count,key);
   if(idx != NOT_FOUND)
   {
       for(int j=idx;j<count-1;j++)
       {
           arr[j] = arr[j+1];
       }
         
       return true;
   }
     
   return false;
   }
  
   public static int[] upSize( int[] fullArr )
   {
   int biggerArr[] = new int[2*fullArr.length];
   for(int i=0;i<fullArr.length;i++)
       biggerArr[i] = fullArr[i];
   return biggerArr;
         
   }
  
   // COPY IT FROM YOUR LAB#3 SOLUTION. USE IT IN REMOVE
   static int indexOf( int[] a, int count, int key )
   {
       for (int i = 0; i<count; i++)
{
if (a[i] == key)
   return i;
}
       return NOT_FOUND;
   }
} // END CLASS
//end of program

Output:

Input file:

Output:

Add a comment
Know the answer?
Add Answer to:
Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int...

    must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int [] arr); public static void quickSort(int [] arr); public static void mergeSort(int [] arr); The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: //merge method //merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely,...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • JAVA getting the following errors: Project4.java:93: error: ']' expected arr[index] = newVal; // LEAVE THIS HERE....

    JAVA getting the following errors: Project4.java:93: error: ']' expected arr[index] = newVal; // LEAVE THIS HERE. DO NOT REMOVE ^ Project4.java:93: error: ';' expected arr[index] = newVal; // LEAVE THIS HERE. DO NOT REMOVE ^ Project4.java:93: error: <identifier> expected arr[index] = newVal; // LEAVE THIS HERE. DO NOT REMOVE ^ Project4.java:94: error: illegal start of type return true; ^ Project4.java:98: error: class, interface, or enum expected static int bSearch(int[] a, int count, int key) ^ Project4.java:101: error: class, interface, or...

  • Here is the indexOf method that I wrote: public static int indexOf(char[] arr, char ch) {...

    Here is the indexOf method that I wrote: public static int indexOf(char[] arr, char ch) {            if(arr == null || arr.length == 0) {                return -1;            }            for (int i = 0; i < arr.length; i++) {                if(arr[i] == ch) {                    return i;                }            }        return -1;       ...

  • You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement...

    You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement this method return new int[] {}; }    There is a utility method provided for you with the following signature. You may use this method to convert a list of integers into an array. public static int[] convertIntegers(List<Integer> integers) Provided code import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class MatrixSearch { // This method converts a list of integers to an array...

  • I'm trying to find out what is wrong with my code? package DriverClass; public class DriveClass...

    I'm trying to find out what is wrong with my code? package DriverClass; public class DriveClass { public static void main(String[] args) { int a[] = {3, 2, 5, 6, 1}; InsertionSortClass insertion = new InsertionSortClass(); System.out.print("The original list : "); System.out.println(); insertion.printArray(a); System.out.println(); System.out.println("The list after insertionSort : "); System.out.println(); insertion.insertionSort(a); } } package DriverClass; public interface SortADTInterface { public void insertionSort(int arr[]); public void printArray(int arr[]); } package DriverClass; public class InsertionSortClass implements SortADTInterface{ public void insertionSort(int[] arr)...

  • 2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert a...

    2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert all elements of array in a hashtable For every element in array: counter0 a. b. c. .Look for array[i] . Look for array [幻 + k in the hash map, if found then increment counter. -k in the hash map, if found then increment counter. Remove arrayli] from hash table. d. return counter For example: Input : array[] {1, 5, 3, 4, 2), k 3 Output:...

  • Consider the following method. public static ArrayList<Integer mystery(int n) ArrayList<Integer seg - new ArrayList<IntegerO; for (int...

    Consider the following method. public static ArrayList<Integer mystery(int n) ArrayList<Integer seg - new ArrayList<IntegerO; for (int k = n; k > 0; k--) seq.add(new Integer(k+3)); return seq What is the final output of the following Java statement? System.out.println(mystery(3)); a. [1,2,4,5) b. [2,3,4,5) c. [6,5,4,3] d. [7, 7, 8, 8] e. [7,8,9, 8) O Consider the following method: public static int mystery(int[] arr, int k) ifk-0) return 0; }else{ return arr[k - 1] + mystery(arr, k-1):) The code segment below is...

  • Hi I need some help on this lab. The world depends on its successfull compilation. /*...

    Hi I need some help on this lab. The world depends on its successfull compilation. /* Lab5.java Arrays, File input and methods Read the comments and insert your code where indicated. Do not add/modify any output statements */ import java.io.*; import java.util.*; public class Lab5 { public static void main (String[] args) throws Exception { final int ARRAY_MAX = 30; // "args" is the list of tokens you put after "java Project3" on command line if (args.length == 0 )...

  • Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong...

    Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong here is what i was told that was needed. Ill provide my code at the very end. Here is what is missing : Here is my code: public class GSL { private String arr[]; private int size; public GSL() {     arr = new String[10];     size = 0; } public int size() {     return size; } public void add(String value) {    ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT