0

What is the error in this program?

Array elements are changed their position. Why duplicate element is added to array? https://code.sololearn.com/c84UuPu2nOrl/?ref=app

12th Jul 2023, 5:05 PM
KGS Sumanth
KGS Sumanth - avatar
4 Answers
0
Hellu, if you want to delete you can use the continue statement, something like this int[] a=new int[]{50,100,200,250,500,750,1000}; nt del=500; for(int i=0;i<a.length;i++){ if(del==a[i]){ // if your number is in the list then continue // our system.out.print will get ignored and the loop will keep going and try again from the top again continue; } System.out.print(a[i]+" "); }
16th Jul 2023, 9:46 PM
JavaBobbo
JavaBobbo - avatar
+ 1
Alright, let's break down the code: First, the code defines an array of integer, a variable "del" with value of 500 and then loop through each element of the array. 2nd, I'd like to change the if statement in the code to this, for readability purposes, and to make it a little faster: if(del == a[i] && i+1<a.length) { a[i] = a[i+1]; } the code checks whether the del is equal to any elements of the array.. if it is, it then gets replaced by the element that is next to the current element.. Elements in an array can be replaced with a specific value, but the value should be the same type of the elements.
12th Jul 2023, 5:36 PM
Dragon RB
Dragon RB - avatar
+ 1
If you want to remove an element of an array, my solution is to using a list, and then transfer it to array.. Since array size are fixed and cannot be changed, while lists can.
12th Jul 2023, 5:39 PM
Dragon RB
Dragon RB - avatar
+ 1
Anyways, your code does not result in an error or raises exception, what do you mean?
12th Jul 2023, 5:42 PM
Dragon RB
Dragon RB - avatar