Shibaku Shibaku - 2 months ago 5
Java Question

How to check if three user-input words in a string are identical?

The following code alphabetizes three words in a user input string.

Example: cat ant dog

= ant cat dog

What I'm trying to do, is make it so that if the three words are completely identical, it'll print out "these words are the exact same" or something on the lines of that.

I'm not quite sure how to go about doing that. Any help or advice would be appreciated, thank you!

final Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter three words : ");
final String words = keyboard.nextLine();
final String[] parts = words.split(" ");
System.out.print("In alphabetical order those are: ");
alphabetizing (parts);
for ( int k = 0; k < 3; k++ )
System.out.print( parts [k] + " " );

}

public static void alphabetizing( String x [] )
{
int word;
boolean check = true;
String temp;

while ( check )
{
check = false;
for ( word = 0; word < x.length - 1; word++ )

{
if ( x [ word ].compareToIgnoreCase( x [ word+1 ] ) > 0 )
{
temp = x [ word ];
x [ word ] = x [ word+1];
x [ word+1] = temp;
check = true;

}
}
}
}
}

Answer
final String[] parts = words.split(" ");

if(parts[0].equals(parts[1]) && parts[1].equals(parts[2]) {
     System.out.println("These words are the exact same");
}

.equals compares the contents of Strings. If string 1 equals string 2 and string 2 equals string 3, string 1 equals string 3 by the transitive property.