Как сортировать пользовательские имена строк в алфавитном порядке, используя String.equals и String.compareTo

Этот вывод программы должен быть:

Enter first : Alexis
Enter Second : Zach
Enter Third : Cassie

Here are sorted the sorted name:

Alexis

Cassie

Zach

но если имена идентичны, он должен вывести сообщение об ошибке, в котором говорится, что имена идентичны.

Пример Введите имя 1 Алексис Введите имя 2 Алексис Введите имя 3 Кэти

Имена один и два идентичны.

import java.util.Scanner;
import java.util.Arrays;


public class AlexisPriceAssignment6
{
        public static String input = " ";
        public static String input2 = " ";
        public static String input3 = "";


    public static void Greet()
    {
        System.out.println("Welcome to Alexis Price's Name Sorter.");
        System.out.println("All names must be unique.");

    }
    public static void Uinput()
    {
          Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter the first name: ");
        input = keyboard.nextLine();
        char one = input.charAt(0);

        System.out.print("Enter the second name: ");
        input2 = keyboard.nextLine();
        char two = input2.charAt(0);

        System.out.print("Enter the third name: " );
        input3 = keyboard.nextLine();
        char three = input3.charAt(0);

        System.out.println();
        if (input.equals(input2) )
        {
            System.out.println(input + " is the same as "+ input2);
        }
        if ( input.equals(input3))
        {
           System.out.println(input + " is the same as "+ input3);
        }
        if (input2.equals(input3))
        {
            System.out.println(input2 + " is the same as "+ input3);
        }
        if (input!=(input2))
        {
            sort();
        }


    }

    public static void sort()
    {
        System.out.println("Here are the sorted names.");

        char charArray [] = input.toCharArray();
        Arrays.sort(charArray);
        String sortedString = new String(charArray);
        System.out.println(sortedString);


    }


    public static void main(String[] args)
    {
        Greet();
        Uinput();


    }

}

person Alexis Marie    schedule 07.02.2018    source источник
comment
Вам не нужны String.equals и String.compareTo. compareTo соответствует equals, поэтому a.compareTo(b) == 0 <=> a.equals(b).   -  person Andy Turner    schedule 07.02.2018
comment
В задании сказано, что я должен использовать String.equals и String.compareTo.   -  person Alexis Marie    schedule 07.02.2018


Ответы (2)


Чек:

    if (input!=(input2))
    {
        sort();
    }

одновременно неправильно, потому что String использует метод .equals() для сравнения, и бесполезно, потому что вы уже проверили все три комбинации, сравнив каждую пару напрямую. Просто вызовите метод sort() после 3 операторов if.

person NiVeR    schedule 07.02.2018

Использование TreeSet делает решение масштабируемым

  • Элементы по умолчанию в TreeSet отсортированы по алфавиту. Порядок можно изменить
  • Для проверки уникальности используйте метод tSet.contains()
person mc20    schedule 07.02.2018