Search code examples
javasortingalphabetical

Sort three letters alphabetically


Currently, I am a student beginning to learn java. I am not familiar with arrays or any complex methods. My teacher wants us to do it this way to understand the logic involved, so I can't use a built-in sort function. Sometimes my code works. For example, when I input "iea", it prints "aei", which is correct. However, sometimes when I enter inputs like "abc", for example, it just prints "c" as the middle value. Help? I'm a noob.

import java.util.*;
public class SortThreeLetters {

  public static void main(String[]args){
    Scanner sc = new Scanner(System.in);
    char largest = ' '; 
    char middle = ' ';
    char min = ' ';
    String word;
    System.out.println("Enter three lower case letters: ");
    word = sc.nextLine();

    char letter1 = word.charAt(0);
    char letter2 = word.charAt(1);
    char letter3 = word.charAt(2);

    if ( letter1 > letter2 && letter1 > letter3 ){
      largest = letter1;

      if(letter2 > letter3){
        middle = letter2;
        min=letter3;
      }
      else if (letter3>letter2){
        middle = letter3;
        min=letter2;
      }
    }


    else if ( letter2 > letter1 && letter2 > letter3 ){
      largest = letter2;

      if(letter3>letter1){
        letter3=middle;
        letter1=min;
      }
      else if (letter1>letter3){
        letter1 = middle;
        letter3 = min;
      }
    }

    else if ( letter3 > letter1 && letter3 > letter2 ){
      largest = letter3;

      if(letter2>letter1){
        letter2 = middle;
        letter1 = min;

      }
      else if (letter1>letter2){
        letter1 = middle;
        letter2 = min;

      }
    }
    System.out.println(min+""+middle+""+largest);



  }


}

Solution

  • if ( letter1 > letter2 && letter1 > letter3 ){
      largest = letter1;
    
      if(letter2 > letter3){
        middle = letter2;
        min=letter3;
      }
      else if (letter3>letter2){
        middle = letter3;
        min=letter2;
      }
    }
    
    
    else if ( letter2 > letter1 && letter2 > letter3 ){
      largest = letter2;
    
      if(letter3>letter1){
       middle=letter3;
       min=letter1;
      }
      else if (letter1>letter3){
        middle=letter1;
        min=letter3;
      }
    }
    
    else if ( letter3 > letter1 && letter3 > letter2 ){
      largest = letter3;
    
      if(letter2>letter1){
        middle=letter2;
        min=letter1;
    
      }
      else if (letter1>letter2){
        middle=letter1;
        min=letter2;
    
      }
    }