Tuesday, 10 September 2013

Replacing a number in an array if duplicates are found

Replacing a number in an array if duplicates are found

Make the user enter 5 integer values into the array in the main method.
Pass array into a separate function. There, check for duplicated values in
the array. If duplicates are found, eliminate the duplicate integer and
replace it with -1. Print the processed array back in the main method.. So
far I have done the code, but I do not know how to eliminate and replace
after comparision. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
}
}

No comments:

Post a Comment