我已经扫描了一个 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();
关于java - 使用前导空格打印来自扫描仪的字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45779974/