【问题标题】:How to check if three user-input words in a string are identical?如何检查字符串中的三个用户输入单词是否相同?
【发布时间】:2017-01-31 17:42:49
【问题描述】:

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

例子:

猫蚁狗

输出:

蚂蚁猫狗

我正在尝试做的是,如果这三个词完全相同,它会打印出“这些词完全相同”或类似的内容。

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

    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;

                      }
              }
        }
  }

【问题讨论】:

标签: java string if-statement


【解决方案1】:
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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多