Reputation: 23
I get an extra comma on the end of my string after the user inputs their text. How do I get rid of the last comma? The good old fence post problem, but I'm stuck on the fence.
import java.util.Scanner;
public class fencepost {
public static void main(String[] args) {
System.out.print("Enter a line of text: ");
Scanner console = new Scanner(System.in);
String input = console.nextLine();
System.out.print("You entered the words: ");
Scanner linescanner = new Scanner(input);
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
System.out.print(", ");
}
}
}
I get as output "hello, there," with an extra comma after there.
Upvotes: 0
Views: 903
Reputation: 1668
Add an if
statement inside your loop to determine if there's still a next line, if so, then add a comma, otherwise, don't add one:
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
if (linescanner.hasNext()) {
System.out.print(", ");
}
}
Upvotes: 3