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...
Im in a java class and having trouble with assigning the seat to a specific number...
Im in a java class and having trouble with assigning the seat to a specific number from the array.. Below are the instructions I was given and then the code that I have already.   ITSE 2321 – OBJECT-ORIENTED PROGRAMMING JAVA Program 8 – Arrays and ArrayList A small airline has just purchased a computer for its new automated reservations system. You have been asked to develop the new system. You are to write an application to assign seats on flight...
** 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 Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
(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...
Having some trouble with this python question. An answer would be greatly appreciated! #Write a function...
Having some trouble with this python question. An answer would be greatly appreciated! #Write a function called are_anagrams. The function should #have two parameters, a pair of strings. The function should #return True if the strings are anagrams of one another, #False if they are not. # #Two strings are considered anagrams if they have only the #same letters, as well as the same count of each letter. For #this problem, you should ignore spaces and capitalization. # #So, for...
I'm having trouble trying to create the italian, polish, and netherlands flag in C Here's my...
I'm having trouble trying to create the italian, polish, and netherlands flag in C Here's my code so far: #include<stdio.h> int main(){    int country_choice;    fprintf(stderr, "Enter the country_code of the chosen flag.(1 for Poland, 2 for Netherlands, 3 for Italy)");    fscanf(stdin, "%d", &country_choice);    switch (country_choice) { case 1: printf("Poland Flag\n"); printf("%c%c%c", 255,255,255); printf("%c%c%c", 220,20,60);    break;       case 2: printf("Italian Flag\n"); printf("%c%c%c", 0,146,70); printf("%c%c%c", 225,255,255); printf("%c%c%c", 206,43,55); break;    case 3: printf("Netherlands Flag\n"); printf("%c%c%c", 174,28,40);...
C# Arrays & methods I'm having trouble implementing the GetIntArrayFromUser method in the following problem: Create...
C# Arrays & methods I'm having trouble implementing the GetIntArrayFromUser method in the following problem: Create a method AverageIntArray that takes an array of integers and calculates and returns the average of all values in the array as a double Write a program that uses GetIntArrayFromUser method to get an array of 7 numbers, then calls the AverageIntArray method to get the average then prints all values in the array that are greater than the average.                 Sample run:                                ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT