vendredi 19 avril 2019

Understanding code logic in alphabetical sorting

I have problem understanding how this code sorts the cities into alphabetical order. I don't understand the logic in the if loops and if someone explain to me how the "switching" works and why the first and last if block statements are the same?

I tried attempting this problem myself but my logic was flawed and I don't get how this logic works.

I know this could be done simpler with arrays and sorting that I have seen but I am a beginner in Java and still trying to learn if statements and strings.

Thank you.

import java.util.Scanner;
public class Cars {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter first city");
        String first = sc.nextLine();
        System.out.println("Enter second city");
        String second = sc.nextLine();
        System.out.println("Enter third city");
        String third = sc.nextLine();


        String temp = "";
        if(first.compareTo(second)>0) {
            temp = second;
            second = first;
            first = temp;
        }
        if(second.compareTo(third) > 0) {
            temp = third;
            third = second;
            second = temp;
        }
        if(first.compareTo(second) > 0) {
            temp = second;
            second = first;
            first = temp;
        }
        System.out.println("alphabetical order" + " " + first + " " + second +" " + third);
    }
}

Aucun commentaire:

Enregistrer un commentaire