I'm working on code that shows the simple operation of an array. I can't seem to make it work at the part of re-inserting a deleted element inside my created array. My goal is to put another element inside another deleted element (when I delete an element it becomes 0). My insert case just tells the duplicate input, it does not let me resume in the deleted element at a certain position.
case 2:
{
if (limit1 < 5 || limit1 > 20){
System.out.println("Error: Invalid Array Limit");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
else{
System.out.println("Enter the " + array.length + " numbers now.
Or enter -1 to exit");
int i = 0;
while(i < array.length){
array[i] = in.nextInt();
boolean dups = false;
if(array[i] != -1){
for(int k = 0; k < i; k++)
if(array[k] == array[i])
{
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if(!dups){
i++;}
}
else{
array[i] = 0;
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
System.out.println("You have entered the "+ limit1 + " numbers");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
Another problem is, if I input a sentinel value (-1), it just makes the current input position 0. I just wish to exit the case not put a 0 at the position
I see some problems with your code. Using
switch
statements without anybreak
statements is not a good practice. You can easily refactor your method to use a while loop like this:This should also exit your program whenever user presses
0
.I see a problem in your Insertion into array block. You seem to be assigning value received from input directly to
array[i]
. What's the point of checking if it's a duplicate value after assigning it toarray[i]
. I think you should do something like this:Regarding exiting on providing
-1
, You should probably remove this linearray[i] = 0
in order to not assign0
toarray[i]
: