Java 检查输入的字符串长度是否等于三

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19440918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:11:10  来源:igfitidea点击:

Check if string length entered is equal to three

javastringchar

提问by user2892900

I need to create a code that checks if the input from the user is equal to a double literal length 3. my if statement is where i am having trouble. Thanks

我需要创建一个代码来检查来自用户的输入是否等于双精度文字长度 3。我的 if 语句是我遇到问题的地方。谢谢

Scanner stdIn= new Scanner(System.in);
String one;
String two;
String three;

System.out.println("Enter a three character double literal ");
one = stdIn.nextLine();

if (!one.length().equals() "3")
{
  System.out.println(one + " is not a valid three character double literal");
}

回答by newuser

Comparison

比较

if (one.length() != 3)

instead of

代替

if (!one.length().equals() "3")

回答by Jeroen Vannevel

if (!(one.length().equals(3)) {
    System.out.println(one + " is not a valid three character double literal");
}

You have to place the 3as an argument to the equalsfunction (ittakes an argument).

您必须将 放置3equals函数的参数(需要一个参数)。

More common is to use ==when comparing numbers though.

更常见的是==在比较数字时使用。

if (!(one.length() == 3) {
    System.out.println(one + " is not a valid three character double literal");
}

or more concise:

或更简洁:

if (one.length() != 3) {
    System.out.println(one + " is not a valid three character double literal");
}

回答by Tyler Iguchi

You don't need to use .equals() as the length method returns an int.

您不需要使用 .equals() 作为 length 方法返回一个 int。

if ( one.length() != 3 ) { do something; }

回答by Dulith De Costa

if (one.length() != 3)

if (one.length() != 3)

if (!(one.length().equals(3))

if (!(one.length().equals(3))

Both these ways work.

这两种方式都有效。

For more details please refer this.

有关更多详细信息,请参阅此。

https://www.leepoint.net/data/expressions/22compareobjects.html

https://www.leepoint.net/data/expressions/22compareobjects.html