I have this code:
Set<String> uniquePairs = new HashSet<String>();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.useDelimiter(System.getProperty("line.separator"));
for(int i=0; i<t ;++i) {
if(sc.hasNext()) {
String element = sc.next();
uniquePairs.add(element);
System.out.println(uniquePairs.size());
}
}
Input:
5
john tom
john mary
john tom
mary anna
mary anna
My Output (stdout)
1
2
3
3
4
Expected Output
1
2
2
3
3
Why it differs? Is it due to Scanner$nextLine();
?
However, I get correct output if I perform following changes:
Remove the line:
sc.useDelimiter(System.getProperty("line.separator"));
Replace the line:
String element = sc.next();
with:
String element = sc.next() + " " + scan.next()j
Please clarify the same?
Here is the code which is giving you the wrong output:
Set<String> uniquePairs = new HashSet<String>();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.useDelimiter(System.getProperty("line.separator"));
for(int i=0; i<t ;++i) {
if(sc.hasNextLine()) {
String element = sc.nextLine();
uniquePairs.add(element);
System.out.println(uniquePairs.size());
}
Output:
1
2
3
3
4
The issue is once you read the int
value, new line character
is left behind and gets read in the loop and produces wrong result. You can read that new line character
using a nextLine()
call and ignore it. Then use the nextLine()
method as per the requirement.
Here is the code producing the correct result.
Set<String> uniquePairs = new HashSet<String>();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine(); // Ignore the next line char.
for(int i=0; i<t ;++i) {
if(sc.hasNextLine()) {
String element = sc.nextLine();
uniquePairs.add(element);
System.out.println(uniquePairs.size());
}
Output:
1
2
2
3
3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.