Question

Building Each Exercise Driver Download the drivers (ExerciseX.java) and start by reading the code. Notice in...

Building Each Exercise Driver

Download the drivers (ExerciseX.java) and start by reading the code. Notice in Exercise1.java’s main how each method for the problems below have already been invoked for you (Skeleton Level: Strong). As you complete additional exercises, notice the comments in each file. As exercises progress, you’ll be required to uncomment lines in main or even build parts of the main driver yourself. We’ll start with skeleton files that are almost complete, and then look at drivers where you need to provide additional code to get things to function correctly.

Exercise One: Searching, Containing and Finding Elements

Download the Driver “Exercise1.java”. We’re going to work on a few functions here, and I’ve already defined the few in question and invoked them from main. In future sections, this will be your responsibility. Lets consider the first function, contains()…

Define the following function in your Exercise1.java code…

public static boolean contains(int[] input, int target)

This function takes an array and a target integer, and returns true if the integer is found in the array, false otherwise.

Walk over the array looking for target; return true if found

Define the following function, using contains()

public static int indexOf(int[] input, int target)

i.This function takes an array as input and returns the index of the first occurrence of target in the input array, or -1 if not found

ii.Build this indexOf() function by calling contains, which you’ve already made above.

Define the following function, using contains()

public static int count(int[] input, int target)

i.This function counts the number of occurrences of target in the input array.

For example, given {1,3,4,5, 1}, the element 1 has a count of 2, whereas the element 6 has a count of 0.

You should try to use contains() here in this function as well.

Define the following function, using count()

public static void duplicates(int[]input, int[] output)

i.This function finds all numbers that occur more than once in the input list and puts them (once) in the output list.

For example, {3,3,3,4,4,5} as input produces {3,4,0,0,0,0} in output

ii.To accomplish this, use the counts function above…

Use counts() to determine if, say, “3” occurs more than once in the input

If it does, use counts() to determine if you’ve already put a “3” in the output.

----

"Ex 1 java file"

// Skeleton file for use with basic array algorithms, such as:// contains, indexOf, count and duplicates.//// Skeleton Level: Strong.// You only need to fill in existing functions// below to complete this driver, with no changes to main.//import java.util.Arrays;
public class Exercise1 {

//Notice that in this main, each of the functions have been called for youpublic static void main(String[] args) {

int[] data = {1,3,5,4,7,9,1,3};int[] output = new int[data.length];
System.out.println("Does our array contain a '1':"+contains(data,

1)); //true

System.out.println("Does our array contain a '0':"+contains(data,

0)); //false

System.out.println("What is the index of '4'? " + indexOf(data, 4));

//3

System.out.println("The number of occurrences of '1'? " +

count(data, 1)); //2

duplicates(data, output);System.out.println("After removing duplicates from data:");System.out.println(Arrays.toString(output));

}public static boolean contains(int[] input, int target) {

//todo: see labreturn false;

}public static int indexOf(int[] input, int target) {

//todo: only find the indexOf a target if we contain() itreturn -1;

}public static int count(int[] input, int target){

int retVal = 0;//todo: only try to count a number that we contain()
return retVal;

}public static void duplicates(int[] input, int[] output) {

//todo: Transfer items once from the arrays:input and output.//Transfer items from input to the output array IF:// only if newArray.count(target) == 0 //ie, we haven't put this

in yet

// only if newArray.indexOf(target) == -1 //not found in

newArray, or

// only if newArray.contains(target) == false //does not exist in

the new array}}

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

import java.util.Arrays;

public class Exercise {
    //Notice that in this main, each of the functions have been called for you
    public static void main(String[] args) {
        int[] data = {1,3,5,4,7,9,1,3};
        int[] output = new int[data.length];
      
        System.out.println("Does our array contain a '1':"+contains(data, 1)); //true
        System.out.println("Does our array contain a '0':"+contains(data, 0)); //false
        System.out.println("What is the index of '4'? " + indexOf(data, 4));    //3
        System.out.println("The number of occurrences of '1'? " + count(data, 1)); //2
      
        duplicates(data, output);
        System.out.println("After removing duplicates from data:");
        System.out.println(Arrays.toString(output));
    }
    public static boolean contains(int[] input, int target) {
        int trueCount = 0;
        int falseCount = 0;
      
        for (int i = 0; i < input.length; i++) { //iterate over array
            if (input[i] == target) { //if the array contains the target number
                trueCount++; //set boolean true
               } else {
                falseCount++; //set boolean false
               }
           }
      
        if (trueCount > 0) {
            return true; //if there are any trues, then it is true
        }   else {
            return false; //none true, is false
        }
      
    }
  
    public static int indexOf(int[] input, int target) {
        int i = 0;
        int retVal = -1;
      
        if (contains(input,target) == true) { //if it is contained
           for ( i = 0; i < input.length; i++) { //iterate over array
            if (input[i] == target) { //if the array contains the target number
                retVal = i; //set index to retVal
               }
            }
        }
      
        return retVal; //return index
        }
    public static int count(int[] input, int target){
        int retVal = 0;
      
        if (contains(input,target) == true) { //if it is contained
             for (int i = 0; i < input.length; i++) { //iterate over array
            if (input[i] == target) { //check for target #
                retVal++; //add count for every
            }
           }
        }
  
        //todo: only try to count a number that we contain()
      
        return retVal;
    }
    public static void duplicates(int[] input, int[] output) {
      
        Exercise newArray = new Exercise();
      
        for (int i = 0; i < input.length; i++) { //iterate over array
            if (newArray.count(input, i) == 0 || newArray.indexOf(input,i) == -1 ||
            newArray.contains(input,i) == false) { //all conditions to move over to output
                output[i] = input[i]; //move over to output
            } //otherwise the index is empty, or 0
        }
    }
}


Add a comment
Know the answer?
Add Answer to:
Building Each Exercise Driver Download the drivers (ExerciseX.java) and start by reading the code. Notice in...
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
  • The following code skeleton contains a number of uncompleted methods. With a partner, work to complete...

    The following code skeleton contains a number of uncompleted methods. With a partner, work to complete the method implementations so that the main method runs correctly: /** * DESCRIPTION OF PROGRAM HERE * @author YOUR NAME HERE * @author PARTNER NAME HERE * @version DATE HERE * */ import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class ArrayExercises { /** * Given a random number generator and a length, create a new array of that * length and fill it from...

  • Problem: Use the code I have provided to start writing a program that accepts a large...

    Problem: Use the code I have provided to start writing a program that accepts a large file as input (given to you) and takes all of these numbers and enters them into an array. Once all of the numbers are in your array your job is to sort them. You must use either the insertion or selection sort to accomplish this. Input: Each line of input will be one item to be added to your array. Output: Your output will...

  • please edit my java code perferably on jgrasp version 50.0 , wont complie correctly :( the...

    please edit my java code perferably on jgrasp version 50.0 , wont complie correctly :( the program is supposed to read from my input file and do the following        1) print out the original data in the file without doing anything to it.        2) an ordered list of all students names (last names) alphabetically and the average GPA of all student togther . 3) freshman list in alphabeticalorder by last name with the average GPA of the freshmen...

  • What is wrong with my code, when I pass in 4 It will not run, without...

    What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error   required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...

  • Implement the function hasDuplicates. Input will be given as a line containing a positive integer n,...

    Implement the function hasDuplicates. Input will be given as a line containing a positive integer n, followed by n rows, each containing a string. The output should be either the word true if there are any duplicates among these strings or false if there are not. Your code should work well on long lists of strings. Use the following set-up to write the code in JAVA import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) {...

  • I need help making this work correctly. I'm trying to do an array but it is...

    I need help making this work correctly. I'm trying to do an array but it is drawing from a safeInput class that I am supposed to use from a previous lab. The safeInput class is located at the bottom of this question I'm stuck and it is not printing the output correctly. The three parts I think I am having most trouble with are in Bold below. Thanks in advance. Here are the parameters: Create a netbeans project called ArrayStuff...

  • Hello, Could you please input validate this code so that the code prints an error message...

    Hello, Could you please input validate this code so that the code prints an error message if the user enters in floating point numbers or characters or ANYTHING but VALID ints? And then could you please post a picture of the output testing it to make sure it works? * Write a method called evenNumbers that accepts a Scanner * reading input from a file with a series of integers, and * report various statistics about the integers to the...

  • IN JAVA please Given a sorted array and a target value, return the index if the...

    IN JAVA please Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. Your code will be tested for runtime. Code which does not output a result in logarithmic time (making roughly log(2) N comparisons) will fail the tests. A sample main function is provided so that you may test your code on sample inputs. For testing purposes, the...

  • 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:...

  • 1. What is the output when you run printIn()? public static void main(String[] args) { if...

    1. What is the output when you run printIn()? public static void main(String[] args) { if (true) { int num = 1; if (num > 0) { num++; } } int num = 1; addOne(num); num = num - 1 System.out.println(num); } public void addOne(int num) { num = num + 1; } 2. When creating an array for primitive data types, the default values are: a. Numeric type b. Char type c. Boolean type d. String type e. Float...

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