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

时间:2013-10-18 03:04:03

标签: java string char

我需要创建一个代码来检查来自用户的输入是否等于双字面长度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");
}

4 个答案:

答案 0 :(得分:8)

Comparison

if (one.length() != 3)

而不是

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

答案 1 :(得分:1)

if (one.length() != 3)

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

这两种方式都有效。

有关详细信息,请参阅此内容。

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

答案 2 :(得分:0)

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

您必须将3作为参数放置到equals函数中(it接受参数)。

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

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

或更简洁:

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

答案 3 :(得分:0)

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

if ( one.length() != 3 ) { do something; }
相关问题