In: Computer Science
Programming Task 1:
Please use the following framework to implement a class for partially filled arrays.
class PartiallyFilledArray
{
double[] content; // content of the array
int size; // actual size of the array
// creating an array whose physical size is 100
PartiallyFilledArray()
{
// your implementation
}
// creating an array whose physical size is given by maxSize
PartiallyFilledArray(final int maxSize)
{
// your implementation
}
// insertion
boolean insert(_____________________)
{
// your implementation
}
// deletion
boolean delete(_____________________)
{
// your implementation
}
// displaying all elements
void display()
{
// your implementation
}
}
Programming Task 2:
Please use the above class to create an empty partially filled array whose maximum size is 2000. (1) Consecutively add 20 different random integer values ranging from -100 to 100 to the array and display the content. (2) Delete the first 3 elements and display the content. Notice that you should not directly use the internal data field of PartiallyFilledArray in your test code.
All the explanations is given in the comments of the code itself.
Code--
import java.util.*;
class PartiallyFilledArray
{
double[]
content; //
content of the array
int
size;
// actual size of the array
// creating an array whose physical size
is 100
PartiallyFilledArray()
{
content=new double[100];
size=-1;
}
// creating an array whose physical
size is given by maxSize
PartiallyFilledArray(final int
maxSize)
{
content=new double[maxSize];
size=-1;
}
// insertion
boolean insert(double data)
{
//if stack is full return
false
if(content.length==(size+1))
return false;
size++;
content[size]=data;
return true;
}
// deletion an element at the given
index
boolean delete(int index)
{
//if it is an invalid index return
false
if(size<index)
return false;
for(int i=index;i<size;i++)
{
content[i]=content[i+1];
}
size--;
return
true;
}
// displaying all elements
void display()
{
System.out.println("Displaying the elements:");
for(int i=0;i<=size;i++)
{
//for convinence I will display only 2 digits
after decimal
System.out.printf("%.2f ",content[i]);
}
System.out.println();
}
}
//programming task 2
public class ArrayTest
{
public static void main(String[] args)
{
//create an array of size
2000
PartiallyFilledArray pfa=new
PartiallyFilledArray(2000);
//consecutively add 20 random
elements
Random r=new Random();
for(int i=0;i<20;i++)
{
pfa.insert((r.nextDouble()*200)-100);
}
//display
pfa.display();
//delete first 3 elements
pfa.delete(0);
pfa.delete(0);
pfa.delete(0);
//display
pfa.display();
}
}
Code(Programming Task-2) Screenshot--
Output (Copied)--
Displaying the elements:
-86.87 32.17 -94.46 28.54 -48.46 26.82 -33.65 34.16 43.66 76.54
-71.30 -1.78 20.33 -21.10 -79.09 -12.55 -14.76 -86.24 -49.63
-46.72
Displaying the elements:
28.54 -48.46 26.82 -33.65 34.16 43.66 76.54 -71.30 -1.78 20.33
-21.10 -79.09 -12.55 -14.76 -86.24 -49.63 -46.72
Note--
Please upvote if you like the effort.