我正在使用扫描仪获取字符串的输入。我的代码如下
String s=scan.next();
if(scan.hasNext()){
s +=scan.nextLine();
}
但问题是它没有读取开头的空格。
示例
Input : Hello World
Output should be : Hello World
Output is :Hello World
请澄清错误并帮助我纠正。
最佳答案
next()
方法用于让我们获取下一个单词(标记),而无需前面的分隔符。扫描仪使用的默认分隔符是一个或多个空格,因此设计时会忽略它。
如果您希望 s
保存整行(或当前行的其余部分),包括分隔符,则跳过 next()
并仅使用 nextLine()
.
String s = scan.hasNextLine() ? scan.nextLine() : "";
但是要注意混合 next
和 nextLine
时经常遇到的问题:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
关于java - 扫描仪一开始就忽略空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566874/