Home > OS >  Program that deletes one integer (or more if there's duplicates) from an array by it's val
Program that deletes one integer (or more if there's duplicates) from an array by it's val

Time:12-12

I need to write a program, which deletes a number of elements from an int array that are equal to some int value. Eventually I should get an array that isn't bigger than the initial one.

I mustn't use lists or any methods that do the deletion directly.

I tried to do this this way and I can't trace the flaw. I suppose, it should be in the last "for" construction but I'm not sure.


import java.util.Arrays;
import java.util.Scanner;

public class App {
public static void main(String\[\] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Array size: ");
int sizeInput = scan.nextInt();

        int[] original = new int[sizeInput];
    
        System.out.print("Array itself: ");
        for (int i = 0; i < sizeInput; i  ) {
            original[i] = scan.nextInt();
        }
    
        System.out.println("Number to be deleted: ");
        int dNumber = scan.nextInt();
    
        int[] newArr = new int[original.length];
    
        for (int i = 0; i < original.length - 1; i  ) {
            int sum = 0;
            if (original[i] == dNumber) {
                newArr[i] = original[i   1];
                sum = sum   1;
            } else if (original[i] != dNumber) {
                newArr[i] = original[i   sum];
            } 
        }
        System.out.println(Arrays.toString(newArr));
    }

}

and here's what I got in my console eventually:

Array size: 5
Array itself: 1 2 3 4 5
Number to be deleted: 2
\[1, 3, 3, 4, 0\]

You see? In the output I get the second "3" for some reason and I also don't get why there's no last element of the initial array.

Please, explain what wrote wrong so that my code doesn't solve the problem. And please explain ho can I solve It. Thanks!

CodePudding user response:

You need a position int for the new array, so you go further only when you set a new value

int[] original = {1, 2, 3, 4, 5};
int dNumber = 2;

int[] newArr = new int[original.length];
int j = 0;
for (int val : original) {
    if (val != dNumber) {
        newArr[j] = val;
        j  ;
    }
}
newArr = Arrays.copyOf(newArr, j); // truncate
System.out.println(Arrays.toString(newArr));
// [1, 3, 4, 5]
  • Related