简体   繁体   English

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

[英]Check if string length entered is equal to three

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. 我需要创建一个代码,检查来自用户的输入是否等于双倍字面长度3。我的if语句是我遇到麻烦的地方。 Thanks 谢谢

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");
}

Comparison 比较方式

if (one.length() != 3)

instead of 代替

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

if (one.length() != 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

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

You have to place the 3 as an argument to the equals function ( it takes an argument). 你要的地方3作为参数传递给equals功能( 需要一个参数)。

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");
}

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

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

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

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