首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用While循环从字符串末尾删除逗号

使用While循环从字符串末尾删除逗号
EN

Stack Overflow用户
提问于 2014-10-13 04:58:33
回答 1查看 866关注 0票数 0

在用户输入文本后,我在字符串的末尾得到一个额外的逗号。怎么去掉最后一个逗号?好旧的篱笆桩问题,但我被困在篱笆上了。

代码语言:javascript
复制
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(", ");

      }

   }
}

我得到输出“你好,那里”,在那里之后有一个额外的逗号。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-13 05:00:26

在循环中添加一个if语句以确定是否还有下一行,如果是,那么添加一个逗号,否则,不要添加一个:

代码语言:javascript
复制
while (linescanner.hasNext()) {
    System.out.print(linescanner.next());
    if (linescanner.hasNext()) {
        System.out.print(", ");
    }

}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26333141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档