Delete a number from an array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Delete a number from an array

The question is: WAP to input 10 numbers into an integer array. Input another number and delete the number from the array assuming that the number is present more than once in the array. I have tried this for a number present only once but if its present once then only the first one is executing. Please help me! My code: import java.util.Scanner; public class Delete { public static void main(String[] args) { int n, x, flag = 1, loc = 0; Scanner s = new Scanner(System.in); int a[] = new int[10]; System.out.println("Enter all the elements:"); for (int i = 0; i < 10; i++) { a[i] = s.nextInt(); } System.out.print("Enter the element you want to delete:"); x = s.nextInt(); for (int i = 0; i < 10; i++) { if(a[i] == x) { flag =1; loc = i; break; } else { flag = 0; } } if(flag == 1) { for(int i = loc+1; i < 10; i++) { a[i-1] = a[i]; } System.out.print("After Deleting:"); for (int i = 0; i < 8; i++) { System.out.print(a[i]+","); } System.out.print(a[8]); } else { System.out.println("Element not found"); } } }

25th May 2018, 3:07 PM
Soham Bhattacharyya
Soham Bhattacharyya - avatar
3 Answers
+ 3
You can try using the remove method or splice. See example below: http://www.java67.com/2012/12/how-to-remove-element-from-array-in-java-example.html
25th May 2018, 5:05 PM
Apple Blossom
Apple Blossom - avatar
0
Thanks for your reply
30th Jul 2018, 2:15 AM
Soham Bhattacharyya
Soham Bhattacharyya - avatar
0
Thanks for your reply
30th Jul 2018, 2:15 AM
Soham Bhattacharyya
Soham Bhattacharyya - avatar