I created a program where users enter a command which are : adding a number to the array or delete an element from the array or print the array. The array size is 10.
Here is the tester class,
import java.util.Scanner;
public class Assignment7 {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
final int MAX = 10;
Numbers nums = new Numbers(MAX);
char command;
int value;
System.out.println
("To add an element into the array, type a.");
System.out.println
("To delete an element from the array, type d.");
System.out.println
("To print the current contents of the array, type p.");
System.out.println
("To exit this program, type x.\n");
System.out.print
("Add (a), delete (d), print (p) or exit (x)?:");
command = scan.nextLine().charAt(0);
while (command != 'x') {
if (command == 'a' || command == 'd') {
System.out.print ("Enter a number: ");
value = scan.nextInt();
scan.nextLine();
if (command == 'a')nums.add(value);
else nums.delete(value);
}
else if (command == 'p') nums.print();
else System.out.println ("Not a value input");
System.out.print
("Add (a), delete (d), print (p) or exit (x)?: ");
command = scan.nextLine().charAt(0);
}
System.out.println ("Program Complete");
}
}
And here is my other class,
import java.util.*;
public class Numbers{
private int[] nums;
private int size;
public Numbers(int _size){
this.nums = new int[_size];
}
public void add(int addnum){
if (size == nums.length)
{
System.out.println("Array is full. The value " +addnum + " cannot be added.");
}
else
{
nums[size] = addnum;
size += 1;
}
}
public void delete(int deleteNum){
if(search(deleteNum) == -1)
{
System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
}
else {
for (int i = nums[deleteNum]; i < nums.length -1; i++){
nums[i]= nums[i+1];
}
}
}
public void print(){
String output ="";
for(int str: nums){
output = output + " " + str;
}
System.out.println(output);
}
private int search(int x){
int index = 0;
while(index < size){
if(nums[index] == x)
return index;
index++;
}
return -1;
}
}
Each time I run the program and input a number I want to delete it doesn't delete it. It deletes the number in the index.
For example, if the array inputs are 1,2,3,4,5,6,7,8,9,10 and I want to delete the number 1 it deletes the value that is in the index of 1 which would be the number 2 instead of the number 1.
sizewhen you remove element, maybe that causes some trouble.