Question
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
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 isnt 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 ); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started