简体   繁体   English

如何阅读输入文字? 爪哇

[英]How to read input text ? Java

I need to check if a "user" types in the word "if". 我需要检查“用户”是否键入单词“ if”。 Let me explain, i have this: String text; 让我解释一下,我有这个:字符串文本;

Scanner read = new Scanner(System.in);
System.out.println("type text");
text=read.nextLine();
System.out.println("the text is " +text);

I need to make sure that what is typed in is a the word "if". 我需要确保键入的是单词“ if”。

You need to use String API's contains() or equals() methods as shown below: 您需要使用String API的contains()equals()方法,如下所示:

if(text.contains("if ") || text.contains(" if") || text.contains(" if ")) {
    System.out.println(" Text contains if");
}

The above code works even if the word if is at the start or at the end of the input text . 即使单词if出现在输入text的开头或结尾,上述代码也有效。

If you are looking for the whole word match, then you need to use equals() as shown below: 如果要查找整个单词匹配项,则需要使用equals() ,如下所示:

if(text.equals("if")) {
    System.out.println(" Text equals if");
}

You need to compare the value of text with the value if using equals() like this: 如果使用equals()则需要将text的值与value进行比较:

if(text.equals("if")){
   //Do something
}

Or a better null safe solution would be: 或更好的null安全解决方案将是:

if("if".equals(text)){}

This way if text is null your program won't crash Thanks to @Tancho for the null safe sollution Generally speaking to compare 2 string you need to use equals() Using == you compare 2 objects references not the values 这样,如果文本为null,则您的程序将不会崩溃感谢@Tancho提供的null安全解决方案一般来说,比较2个字符串需要使用equals()使用==可以比较2个对象引用而不是值

If you're looking for an exact match, you should use : 如果您要寻找完全匹配的内容,则应使用:

"if".equals(text)

Not the other way around, because a constant should always be compared to a variable, not the other way around. 并非相反,因为常量应始终与变量进行比较,而不是相反。 You will have : 1. readability 2. safety (as this will never throw a NullPointerException, even if text is null) 您将具有:1.可读性2.安全性(因为即使text为null,也绝不会抛出NullPointerException)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM