Why does the validation on my compareTo method make the output wrong?

108 views Asked by At

For homework one of my methods has to compare the user's first name and last name, and output which comes first alphabetically. I am able to write the code and make everything lowercase and use the compareTo to get an integer, and it works just fine. But when I purposely input a number, the validation somehow makes the output always go to "they both equal each other" when they do not equal each other.

public static void alpha() {
    //takes two names, makes them lowercase, and sorts them using uniCode
    System.out.println("Please input the first name you want me to organize.");
    String firstC = isValidString();
    String fir = firstC.toLowerCase();
    
    System.out.println("Please input the second name you want me to organize.");
    String secondC = isValidString();
    String sec = secondC.toLowerCase();
    
    int uniOut = fir.compareTo(sec);
    if (uniOut > 0) {
        System.out.printf("%s is first alphabetically", secondC);
    } else if (uniOut < 0) {
        System.out.printf("%s is first alphabetically", firstC);
    } else {
        System.out.println("Those names are the same.");
    }
}

public static String isValidString() {
    //validates input as a string and has the user continue to input until it is a string
    Scanner in = new Scanner(System.in);
    while (in.hasNextDouble()) {
        double input = in.nextDouble();
        System.out.printf("%f is not a valid input, please try again.\n", input);
    }
    String s = in.nextLine();
    return s;
}

The isValidString() is another method I have that works perfectly for the other methods in this class, so I don't think that is the problem.

I have tried changing the }else{ to an }else if{ to specify that both strings equal each other and I had a 'buffer' else, and the output still said that the strings were equal.

I tried to input one string correctly the first time, and try the validation on the other (in both ways), but that also gave a weird output, where it would say " is first alphabetically". I do not know why the validation is making the variables act weird, but I cannot think of a way to fix this.

1

There are 1 answers

3
Reilas On

"... compare the user's first name and last name, and output which comes first alphabetically. I am able to write the code and make everything lowercase and use the .compareTo to get an integer ..."

Use the compareToIgnoreCase instead.

String a = "789", b = "123";
int i = Integer.compare(a.compareToIgnoreCase(b), 0);
String s = a + switch (i) {
    case -1 -> '<';
    case 0 -> '=';
    default -> '>';
} + b;

Output

abc<xyz