如何检查字符串中三个用户输入的单词是否相同



下面的代码将用户输入字符串中的三个单词按字母顺序排列。

的例子:

猫蚂蚁狗

输出:

蚂蚁猫狗

我要做的是,如果这三个单词完全相同,它会打印出"这些单词是完全相同的"或类似的东西。

我不太确定该怎么做。任何帮助或建议将不胜感激,谢谢!

    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;
                      }
              }
        }
  }
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比较string的内容。如果字符串1等于字符串2,字符串2等于字符串3,则根据传递性,字符串1等于字符串3。

最新更新