Answer to Question #72892 in Java | JSP | JSF for Atif Haroon

Question #72892
1. Implement an array of 10 integers with following features:
a. Add an element at start
b. Add an element at end
c. Add an element at i-th index
d. Remove an element from start
e. Remove an element from end
f. Remove an element from i-th index
1
Expert's answer
2018-01-28T09:08:44-0500

public class Main {
public static void main(String[] args) {
IntArray a = new IntArray();

System.out.println("Add value 7 at start: ");
a.addAtStart(7);
System.out.println(a);

System.out.println("Add value 5 at a[3]: ");
a.addByIndex(5, 3);
System.out.println(a);


System.out.println("Add value 2 at a[8]: ");
a.addByIndex(2, 8);
System.out.println(a);

System.out.println("Add value 1 at start:");
a.addAtStart(1);
System.out.println(a);

System.out.println("Add value 4 at end:");
a.addAtEnd(4);
System.out.println(a);

System.out.println("Remove value at a[1]:");
a.removeByIndex(1);
System.out.println(a);

System.out.println("Remove value from start:");
a.removeFromStart();
System.out.println(a);

System.out.println("Add value 9 at end:");
a.addAtEnd(9);
System.out.println(a);

System.out.println("Remove value from end:");
a.removeFromEnd();
System.out.println(a);
}
}

=================================

public class IntArray {
private int[] arr;

public IntArray()
{
arr = new int[10];
}
void addByIndex (int value, int index)
{
if(index >= 0 && index <= 9)
{
int[] buffer = new int[this.arr.length];
for(int i = 0; i < this.arr.length; i++)
{
buffer[i] = this.arr[i];
}

this.arr = new int[this.arr.length];

for(int i = 0; i < index; i++)
{
this.arr[i] = buffer[i];
}

this.arr[index] = value;

for(int i = index + 1; i < this.arr.length; i++)
{
this.arr[i] = buffer[i - 1];
}
}
else
{
System.out.println("Incorrect index value!");
}
}

void addAtStart(int value)
{
this.addByIndex(value, 0);
}

void addAtEnd(int value)
{
this.addByIndex(value, this.arr.length - 1);
}

void removeByIndex (int index)
{
int[] buffer = new int[this.arr.length];
for(int i = 0; i < arr.length; i++)
{
buffer[i] = arr[i];
}

this.arr = new int[this.arr.length];

for(int i = 0; i < index; i++)
{
this.arr[i] = buffer[i];
}
for(int i = index + 1; i < arr.length; i++)
{
this.arr[i - 1] = buffer[i];
}

}

void removeFromStart()
{
this.removeByIndex(0);
}

void removeFromEnd()
{
this.removeByIndex(this.arr.length - 1);
}

@Override
public String toString() {
String s = "";
for(int i = 0; i < arr.length; i++)
{
s += arr[i] + " ";
}
return s;
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS