编程语言
首页 > 编程语言> > java-使用前置空格打印来自扫描仪的字符串输入

java-使用前置空格打印来自扫描仪的字符串输入

作者:互联网

我已经扫描了一个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.

解决方法:

Scanner.next()使用默认的定界符,它将捕获任何空白序列.使用Scanner.nextLine()代替:

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

Ideone Demo

标签:java-util-scanner,io,string,java
来源: https://codeday.me/bug/20191025/1931074.html