英文:
.contains() does not work with standard input in java?
问题
以下是翻译好的部分:
我正在使用.contains()
来检查标准输入
,但是似乎对我不起作用。例如,即使我将hi there
作为标准输入,我得到的输出也是:
hi there
没有人喜欢吃豌豆 是 true
我期望还能得到以下输出:
hi there 是 true
<!-- language: lang-java -->
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inp = sc.next();
String fixed = "没有人喜欢吃豌豆";
if (inp.contains("hi there")) {
System.out.println(inp + " 是 " + true);
}
if (fixed.contains("吃")) {
System.out.println(fixed + " 是 " + true);
}
}
我的问题是: 尽管标准输入应该与使用.contains()
的输入匹配,为什么标准输入在.contains()
方法中不起作用,或者我的代码有问题?
英文:
I am using .contains()
to check standard input
, but it seems not to work for me. For example even if I put hi there
as standard input I get:
hi there
nobody likes to eat peas is true
I am expecting to get in addition:
hi there is true
<!-- language: lang-java -->
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
String inp = sc.next();
String fixed = "nobody likes to eat peas";
if (inp.contains("hi there")){
System.out.println(inp + " is " + true);
}
if (fixed.contains(" to eat ")){
System.out.println(fixed + " is " + true);
}
}
My Question is: does standard input not work with the .contains()
method even though the standard input should match the input using .contains()
or is my code wrong?
答案1
得分: 2
扫描器通过将输入视为分成块的方式工作,在每个块之间(称为“标记”)之间是分隔符。
默认情况下,“任何连续的空白序列”都是分隔符。因此,inp
不可能包含 hi there
- 毕竟,如果您直接将该输入提供给程序,第一个标记就是 hi
。那就是 inp
包含的全部内容。然后,对 next()
的第二次调用将返回 there
。
听起来您打算让扫描器将整行视为块,并将换行符视为分隔符。
您所需要做的就是告诉扫描器,一切都会正常:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\r?\n");
// 剩余的代码与平常一样
注意:\r?\n 是正则表达式,表示“可选的 CR,后跟必需的 LF”。这可以捕获Unix/MacOSX风格的换行符 (\n) 以及Windows风格的换行符 (\r\n)。
英文:
Scanners work by treating the input as if it is split into chunks, where in between each chunk (called a 'token') is the delimiter.
Out of the box, 'any sequence of whitespace' is the delimiter. So, inp
couldn't possibly contain hi there
- after all, if you fed that input straight to the program, the first token is hi
. That's all that inp
would contain. A second call to next()
would then return there
.
It sounds like you intend for the scanner to treat entire lines as the chunks, and newline symbols as the delimiter.
All you have to do, is tell scanner about it, and all will be well:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\r?\n");
// rest of your code as normal
NB: \r?\n is regexp for 'an optional CR followed by a required LF'. This catches both unix/macosx style newlines (\n) as well as windows style newlines (\r\n).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论