Reputation: 151
I wanted to check whether the txt file contain duplicate data or not when i click the button load Data.
For example ID, ID in an int.
0001
0002
0003
here is the partial code
while (scnr.hasNextInt())
{
id = scnr.nextInt();
int checkid = id;
if(checkid == id) {
System.out.println("invalid id");
} else{
clients.put(new Integer(id), new Client(id));
}
}
This code doesn't work.
And also, i had tried this method but it is not working too.
if(checkid.matches(id))
{
System.out.println("invalid id");
}
Cannot invoke matches (int) on the primitive type int
i not understand why String type data can use .matches() but int cannot.
what method i can implant to validate the int type data????
Upvotes: 0
Views: 1116
Reputation: 6158
First, you should understand int
is not a class but a primitive type in Java, you can't invoke a method on it.
Second, you want to find duplicate elements, so you should try Set
.
Last, if you are new to programming language, you can try Head First Java; otherwise, you may want to have a look at Thinking In Java
Upvotes: 3
Reputation: 3118
The reason why your code doesn't work is quite obvious: You set checkid
to id
and then check if they are equal. If you want to check every new id against previous ids, you need to keep track of the ids that were already read, e. g. using a List
or a Set
as mentioned before.
Something along theese lines would do:
List<Integer> ids = new ArrayList<>();
while (scnr.hasNextInt()) {
id = scnr.nextInt();
if (ids.contains(id)) {
System.out.println("invalid id");
} else {
ids.add(id);
clients.put(new Integer(id), new Client(id));
}
}
i not understand why String type data can use .matches() but int cannot.
String
is a complex datatype, int
is a primitive datatype that does not support methods. Anyhow, .matches()
wouldn't do the job because it compares against a regular expression. .equals
would be a better choice, but again, not for int
.
Upvotes: -1
Reputation: 145
Here's an example that should work for you. Use a HashSet to store ids and check if the Set contains the id.
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Set<Integer> ids = new HashSet<>();
int id;
while (scnr.hasNextInt()) {
id = scnr.nextInt();
if (ids.contains(id)) {
System.out.println("invalid id");
} else {
ids.add(id);
clients.put(new Integer(id), new Client(id));
}
}
}
}
Upvotes: 0