【问题标题】:Printing a string input from scanner with leading whitespaces使用前导空格从扫描仪打印字符串输入
【发布时间】:2017-08-20 08:18:23
【问题描述】:

我已经扫描了一个 int 类型的输入,然后我尝试获取第二个 String 类型的输入,该输入在开头有空格,并且在打印两个输入时,我希望将第二个输入打印为它是(带有空格)。

class Input{
    public static void main (String[] args) throws java.lang.Exception{

        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();


        String s=sc.next();
        s=s+sc.nextLine();

        System.out.println(n);
        System.out.println(s);
    }
}

输入:

4
      hello world.

预期输出:

4
      hello world.

实际输出:

4
hello world.

【问题讨论】:

    标签: java string io java.util.scanner


    【解决方案1】:

    Scanner.next() 使用默认分隔符,它将捕获任何空白序列。请改用Scanner.nextLine()

    int n = sc.nextInt();
    sc.nextLine();  // consume only the newline
    String s = sc.nextLine();
    

    Ideone Demo

    【讨论】:

      【解决方案2】:

      使用sc.nextLine() 代替 next()。 因为对于nextLine(),要读取的令牌是整行,对于next(),要读取的令牌是下一个单词。

      【讨论】:

        【解决方案3】:

        默认分隔符是一个或多个空格:

        private static Pattern WHITESPACE_PATTERN = Pattern.compile(
                                                        "\\p{javaWhitespace}+");
        

        所以sc.next() 产生"hello"sc.nextLine() 读取当前行的其余部分产生"world"

        您可以将断线字符设置为第二个输入的分隔符并删除

        s = s + sc.nextLine(); 不再需要:

        ...
        sc.useDelimiter(System.lineSeparator());
        String s = sc.next();
        

        【讨论】:

          【解决方案4】:
          import java.util.*;
          class Input{
              public static void main(String[] main){
                  Scanner sc=new Scanner(System.in);
                  int n=sc.nextInt();
                  sc=new Scanner(System.in);
                  String s=sc.nextLine();
                  System.out.println(n);
                  System.out.println(s);
              }
          }
          

          【讨论】:

          • 欢迎。你应该在你的评论中添加一个简短的解释
          猜你喜欢
          • 2014-12-29
          • 2011-08-23
          • 1970-01-01
          • 2012-12-06
          • 1970-01-01
          • 1970-01-01
          • 2018-02-08
          相关资源
          最近更新 更多