简体   繁体   中英

Remove comma from end of String, using While loop

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.

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(", ");
    }

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM