以下代码按字母顺序排列用户输入字符串中的三个单词。
示例:
猫蚂蚁狗
输出:
蚂蚁猫狗
我想要做的是,如果三个单词完全相同,它就会打印出来#34;这些单词完全相同"或类似的东西。
我不太确定如何去做。任何帮助或建议将不胜感激,谢谢!
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;
}
}
}
}
答案 0 :(得分:0)
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比较字符串的内容。如果字符串1等于字符串2而字符串2等于字符串3,则字符串1等于字符串3的传递属性。