I have to write a java program that asks users to enter data values, until they enter a blank line. But I have a problem that I have to enter
twice to stop asking input and i only can solve this problem when adding a System.out.prinln()
line. How can i fix it, pleas help me.
This is my code:
System.out.println("Enter components: ");
Set<String> comps = new Set<>();
while (true) {
String comp = scan.nextLine();
if (comp.equals("")) {
break;
} else {
comps.insert(comp);
scan.nextLine(); // also if i remove this line, the input only asked twice
System.out.println(); // can solve the prob when add this
}
}
When i run my program, it will asks for the input like this:
CodePudding user response:
You only need one Scanner
nextLine
call.
System.out.println("Enter components: ");
Set<String> comps = new Set<>();
while (true) {
String comp = scan.nextLine();
if (comp.equals("")) {
break;
} else {
comps.insert(comp);
}
}
CodePudding user response:
Here you need to feed only one empty line and the loop will break.
String comp = scan.nextLine();
while (!comp.equals("")) {
comps.add(comp);
comp = scan.nextLine();
}