Reputation: 11
I am using the following code and this is giving me a duplicate values in every position of the array So suggest me what to do
String sCurrentLine;
String username[] = new String[30];
String Arrival[] = new String[30];
String Departure[] = new String[30];
int var = 0, var2;
BufferedReader br = new BufferedReader(new FileReader("E:\\Shubham Projects\\Input.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String[] information = sCurrentLine.split(" ");
var2 = information.length + var;
for (int i = var; i < var2; i++) {
System.out.println(i);
username[i] = information[0];
Arrival[i] = information[1];
Departure[i] = information[2];
var++;
}
}
for (int i = 0; i < username.length; i++)
System.out.println(username[i] + " " + Arrival[i] + " " + Departure[i]);
Input:
Jai 10:15 11:10
Jai 10:10 11:00
Veeru 10:10 11:00
Veeru 16:30 18:45
Jai 12:05 12:30
Veeru 12:30 13:25
Veeru 12:45 13:25
Jai 17:25 18:01
Output:
Jai 10:15 11:10
Jai 10:15 11:10
Jai 10:15 11:10
Jai 10:10 11:00
Jai 10:10 11:00
Jai 10:10 11:00
Veeru 10:10 11:00
Veeru 10:10 11:00
Veeru 10:10 11:00
Veeru 16:30 18:45
Veeru 16:30 18:45
Veeru 16:30 18:45
Jai 12:05 12:30
Jai 12:05 12:30
Jai 12:05 12:30
Veeru 12:30 13:25
Veeru 12:30 13:25
Veeru 12:30 13:25
Veeru 12:45 13:25
Veeru 12:45 13:25
Veeru 12:45 13:25
Jai 17:25 18:01
Jai 17:25 18:01
Jai 17:25 18:01
null null null
null null null
null null null
null null null
null null null
null null null
Upvotes: 1
Views: 114
Reputation: 106
Inner for loop is causing the issue because you're grabbing the information from every line three times.
var2 = information.length + var;
for (int i = var; i < var2; i++) {
System.out.println(i);
username[i] = information[0];
Arrival[i] = information[1];
Departure[i] = information[2];
var++;
}
Jai 10:15 11:10
When you read this line, var2 will evaluate to 3 (assuming var is 0). Now it'll run through the for loop three times, giving you your duplicate entries.
Shriram's solution will fix this issue and Amila's response will fix the issue of duplicate entries in the input file.
Upvotes: 1
Reputation: 4411
Make use of set and print the result, because Set won't allow duplicates.
Use the below logic
int count = 0;
while ((sCurrentLine = br.readLine()) != null) {
String[] information = sCurrentLine.split(" ");
// for (int i = 0; i < information.length; i++) {
username[count] = information[0];
Arrival[count] = information[1];
Departure[count] = information[2];
// }
count++;
}
After printing the output the remaining null values are nothing but you have initalized string array with 30. Make use of collection classes for dynamic array. Also i said make use of Set to avoid duplicated
Upvotes: 0
Reputation: 5213
You can use Set
data structure which allows no duplicates.
Try:
Set<String> resultSet = new HashSet<String>(Arrays.asList(username));
resultSet
will have unique Strings.
Upvotes: 2