user2892900
user2892900

Reputation: 29

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

Upvotes: 2

Views: 55386

Answers (4)

Du-Lacoste
Du-Lacoste

Reputation: 12767

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

Upvotes: 1

Tyler Iguchi
Tyler Iguchi

Reputation: 1074

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

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

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

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).

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

Upvotes: 0

newuser
newuser

Reputation: 8466

Comparison

if (one.length() != 3)

instead of

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

Upvotes: 9

Related Questions