Question

In: Computer Science

Having some trouble with this Java Lab (Array.java) Objective: This lab is designed to create an...

Having some trouble with this Java Lab (Array.java)

Objective:

This lab is designed to create an array of variable length and insert unique numbers into it. The tasks in this lab include:

Create and Initialize an integer array
Create an add method to insert a unique number into the list
Use the break command to exit a loop
Create a toString method to display the elements of the array

Task 1:

Create a class called Array, which contains an integer array called ‘listArray’. The integer array should not be initialized to any specific size.

Task 2:

Create a Constructor with a single parameter, which specifies the number of elements that needs to be created for listArray. The listArray needs to be created to this size.

Task 3:

Create a ‘add’ method to class Array which will search through the elements of listArray. A looping mechanism should be used to search the array of elements. If the value passed into add is not already in the list, it should be added. Once the element is added, you need to use the break statement to exit to search so the value isn’t added to each space in the array. If all elements of the array contain non-zero numbers, no more values will be added.

Task 4:

Create a ‘toString’ method to output the non-zero elements of the array. Use the program template and the Sample Output as a reference to guide your application development.

Sample output:

Enter Number of Elements to Create in Array: 10
Enter Number to Add to List (-1 to Exit): 4
4 (added)
Enter Number to Add to List (-1 to Exit): 9
9 (added)
Enter Number to Add to List (-1 to Exit): 21
21 (added)
Enter Number to Add to List (-1 to Exit): 4
4 (duplicate)
Enter Number to Add to List (-1 to Exit): 7
7 (added)
Enter Number to Add to List (-1 to Exit): -1
Array List: 4, 9, 21, 7,

Test Code (ArrayTest.java):

package arraytest;

import java.util.Scanner;



public class ArrayTest 
{
   public static void main(String[] args) 
   {
      int      elements, input;
      Scanner  keyboard = new Scanner( System.in );
      Array    arrayList;
      
      System.out.print( "Enter Number of Elements to Create in Array: " );
      elements = keyboard.nextInt();         // Read number of elements
      arrayList = new Array( elements );     // Instantiate array with no elements
      
      do
      {
         System.out.print( "Enter Number to Add to List (-1 to Exit): " );
         input = keyboard.nextInt();      // Read new Number to add
         if ( input != -1 )
         {
            arrayList.add( input );       // Add to array if not -1
         }
      } while ( input != -1 );
      
      // call toString method to display list
      System.out.println( arrayList );    
   }  
}

Solutions

Expert Solution

PROGRAM CODE:

Array.java

package array;

public class Array {

  

   int listArray[];

   int size;

   Array(int size)

   {

       listArray = new int[size];

       size = 0;

   }

  

   public void add(int value)

   {

       for(int i=0; i<size; i++)

       {

           if(listArray[i] == value)

           {

               System.out.println(value + " (duplicate)");

               return;

           }

       }

       if(size != listArray.length)

       {

           listArray[size++] = value;

           System.out.println(value +" (added)");

       }

   }

  

   @Override

   public String toString() {

       String output = "ArrayList: ";

       for(int i=0; i<size; i++)

       {

           output += listArray[i] + ",";

       }

       return output;

   }

}

ArrayTest.java

package array;

import java.util.Scanner;

public class ArrayTest

{

   public static void main(String[] args)

   {

int elements, input;

Scanner keyboard = new Scanner( System.in );

Array arrayList;

  

System.out.print( "Enter Number of Elements to Create in Array: " );

elements = keyboard.nextInt(); // Read number of elements

arrayList = new Array( elements ); // Instantiate array with no elements

  

do

{

   System.out.print( "Enter Number to Add to List (-1 to Exit): " );

   input = keyboard.nextInt(); // Read new Number to add

   if ( input != -1 )

   {

arrayList.add( input ); // Add to array if not -1

   }

} while ( input != -1 );

  

// call toString method to display list

System.out.println( arrayList );

   }

}

OUTPUT:

Enter Number of Elements to Create in Array: 10

Enter Number to Add to List (-1 to Exit): 4

4 (added)

Enter Number to Add to List (-1 to Exit): 9

9 (added)

Enter Number to Add to List (-1 to Exit): 21

21 (added)

Enter Number to Add to List (-1 to Exit): 4

4 (duplicate)

Enter Number to Add to List (-1 to Exit): 7

7 (added)

Enter Number to Add to List (-1 to Exit): -1

ArrayList: 4,9,21,7,


Related Solutions

Hello! I am having trouble starting this program in Java. the objective is as follows: "...
Hello! I am having trouble starting this program in Java. the objective is as follows: " I will include a text file with this assignment. It is a text version of this assignment. Write a program that will read the file line by line, and break each line into an array of words using the tokenize method in the String class. Count how many words are in the file and print out that number. " my question is, how do...
** USING MATLAB TO PROGRAM The main objective of this lab is to create a game...
** USING MATLAB TO PROGRAM The main objective of this lab is to create a game that involves betting on the sum of two dice. The player will start out with some initial total amount of money. During each round, the player can bet some money that the sum of the two dice will be equal to a certain number. If the player wins the bet, that player adds the amount of the bet to his or her current total....
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
(JAVA) ExceptionSum The objective of this exercise is to create a method that adds all the...
(JAVA) ExceptionSum The objective of this exercise is to create a method that adds all the numbers within an array with an exception you cant sum the 6, and the 7, and the numbers between them cannot be added too, taking into account that whenever a 6 appears will be followed by a 7. If we have an array such that [1,2,3,6,10,9,8,7,5] when we pass it through the method it will give us an int such that the sum will...
Hi, I'm having trouble with answering these organic chemistry lab questions. Please give full answers in...
Hi, I'm having trouble with answering these organic chemistry lab questions. Please give full answers in your own words. Thanks in advance 1. Which of the following solvents: acetone, diethly ether, dichloromethane, pentane, THF, form upper layers or lower layers and which are miscible or immiscible with water during an extraction? 2. What is the consequence of only cooling the recrystallization solution to room temperature instead of 0 degrees celsius. 3. What is the consequence of only cooling the recrysyallization...
Hello, I’m having some trouble making changes to the Cellphone and the associated tester class; Any...
Hello, I’m having some trouble making changes to the Cellphone and the associated tester class; Any help is appreciated ! Cellphone class; -Implement both get and set methods for all 3 attributes or fields of the class - Fields/Attributes are all initialized using the setter methods and there’s no need to initialize them using the contractor. 2) Tester Class; -Create the objects using the default constructor. This is the constructor with no parameter -Call the set methods of all 3...
I have to write a random password generator in Python 3 and im having some trouble...
I have to write a random password generator in Python 3 and im having some trouble writing the code and i dont really know where to start. The prompt goes as such: The problem in this assignment is to write a Python program that uses functions to build (several options of) passwords for the user. More specifically, your program will do the following: 1. Prompt the user for the length of the password to be generated. Call this length lenP....
TrackMinMax i want the generic version based on java For this lab, you will create a...
TrackMinMax i want the generic version based on java For this lab, you will create a generic version of the IntTrackMinMax class you wrote in a previous lab, called TrackMinMax. The API is: Function Signature Description constructor TrackMinMax() constructor check void check(T i) compares i to the current minimum and maximum values and updates them accordingly getMin T getMin() returns the minimum value provided to check() so far getMax T getMax() returns the maximum value provided to check() so far...
Hi, I'm having some trouble with this question, especially part B. Stocks offer an expected rate...
Hi, I'm having some trouble with this question, especially part B. Stocks offer an expected rate of return of 18%, with a standard deviation of 22%. Gold offers an expected return of 10% with a standard deviation of 30%. a) In light of the apparent inferiority of gold with respect to average return and volatility, would anyone hold gold in his portfolio? (4 points) b) Assume that the correlation between Stocks and Gold is -0.5. Find the weights wS and...
Having trouble with the verilog code. Also think my ASM chart may be wrong so some...
Having trouble with the verilog code. Also think my ASM chart may be wrong so some help with that would be great as well thanks. Not sure if the question is linked but its a textbook question. Digital design 6th edition chapter 8 question 10.Link:  https://www.chegg.com/homework-help/Digital-Design-6th-edition-chapter-8-problem-10P-solution-9780134529561
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT