Question: This program fails when two strings are equal. Please fix this problem by adding a else statement. import java.util.Scanner; /** * This Program will sort
This program fails when two strings are equal.
Please fix this problem by adding a "else" statement.
import java.util.Scanner;
/**
* This Program will sort the inputs lexicographically
*
* @author Jay
* @version 01-28-2020
*/
public class P3_16
{
public static void main(String[] args)
{
// representations of strings
String top = "";
String middle = "";
String bottom = "";
Scanner input = new Scanner(System.in);
System.out.println("Enter the 1st string: ");
String firstString = input.nextLine();
System.out.println("Enter the 2nd string: ");
String secondString = input.nextLine();
System.out.println("Enter the 3rd string: ");
String thirdString = input.nextLine();
// This will compare the first strings to the other two strings
if ((firstString.compareTo(secondString) < 0) && (firstString.compareTo(thirdString) < 0))
{
top = firstString;
if (secondString.compareTo(thirdString) < 0)
{
middle = secondString;
bottom = thirdString;
}
else if (secondString.compareTo(thirdString) > 0)
{
middle = thirdString;
bottom = secondString;
}
}
else if ((secondString.compareTo(firstString) < 0 ) && (secondString.compareTo(thirdString)< 0 ))
{
top = secondString;
if (firstString.compareTo(thirdString) < 0 )
{
middle = firstString;
bottom = thirdString;
}
else if (firstString.compareTo(thirdString) > 0 )
{
middle = thirdString;
bottom = firstString;
}
}
else if ((thirdString.compareTo(firstString) < 0 ) && (thirdString.compareTo(secondString)< 0 ))
{
top = thirdString;
if (firstString.compareTo(secondString) < 0 )
{
middle = firstString;
bottom = secondString;
}
else if (firstString.compareTo(secondString) > 0 )
{
middle = secondString;
bottom = firstString;
}
}
System.out.println();
System.out.println(top);
System.out.println(middle);
System.out.println(bottom);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
