【问题标题】:Merging two methods合并两种方法
【发布时间】:2016-10-28 01:34:52
【问题描述】:

我有这段代码是为了按字母顺序排列三个单词。我正在尝试删除底部的方法,并将其添加到上面的代码中。但是,我想不出一种工作方式来做到这一点。任何指导或帮助将不胜感激,谢谢!

    System.out.print("Please enter three words: ");
    final String words = keyboard.nextLine();
    final String[] parts = words.split(" ");

    if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
    System.out.println("All three of those words are the same!");

 } else  {

         System.out.print("In alphabetical order those are: ");
         alphabetizing (parts);
         final int three = 3;
         for (int limit = 0;  limit < three;  limit++) {
         System.out.print(parts[limit] + " ");
         }
  }
  }

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

              for (word = 0;  word < parts.length - 1;  word++) {
                      if (parts[ word ].compareToIgnoreCase(parts[word + 1]) > 0) {
                                  temp = parts[word];
                                  parts[word] = parts[word + 1];
                                  parts[word + 1] = temp;
                                  check = true;

                      }
              }
        }
  }

【问题讨论】:

  • 你为什么要这样做?
  • 您应该将代码提取到更多方法中,而不是相反。
  • @ScaryWombat 这是一个任务。我被要求删除该方法。
  • 我同意@Tom 所说的。 Google for 一个函数应该做一件事
  • 是的,在现实生活中,这个特定的功能应该保持独立。但是,有时将功能结合在一起是有意义的,而 Shibaku 的任务就是在那个时候练习。

标签: java string methods


【解决方案1】:

因为无论如何你都想做。我看不出有什么问题,为什么它不起作用。只需将它添加到调用该方法的 else 语句中,它就可以工作了。

    System.out.print("Please enter three words: ");
    Scanner keyboard = new Scanner(System.in);
    final String words = keyboard.nextLine();
    final String[] parts = words.split(" ");

    if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
        System.out.println("All three of those words are the same!");

    } else {

        System.out.print("In alphabetical order those are: ");

        //boolean check = true; you don't neeed this.
        String temp = "";

        for (int word = 0; word < parts.length - 1; word++) {
            if (parts[word].compareToIgnoreCase(parts[word + 1]) > 0) {
                temp = parts[word];
                parts[word] = parts[word + 1];
                parts[word + 1] = temp;

            }
        }
        final int three = 3;
        for (int limit = 0; limit < three; limit++) {
            System.out.print(parts[limit] + " ");
        }

    }

输出:

Please enter three words: a b c
In alphabetical order those are: a b c 
Please enter three words: a a a
All three of those words are the same!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    相关资源
    最近更新 更多