The Java compiler does not know which branch of an if
statement will be executed. That means that if you initialize a variable in one branch but not the other, the variable is not guaranteed to have a value assigned to it. In your code, all of the variables will of course be initialized, but the compiler has no way of knowing this, hence your error. You can just initialize the three to null
or an empty string. Replace String topString, middleString, bottomString;
with
String topString = null;
String middleString = null;
String bottomString = null;
Additionally, you may want to use some of Java's built-in sorting functionality to do the sorting for you:
import java.util.*;
public class Ordered2
{
public static void main(String[] args)
{
String firstString, secondString, thirdString;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter three different strings.");
System.out.println("The string in the middle order lexicographically will be displayed.");
firstString = keyboard.nextLine();
secondString = keyboard.nextLine();
thirdString = keyboard.nextLine();
String[] array = new String[] {firstString, secondString, thirdString};
Arrays.sort(array);
System.out.println("The second string in lexicographic order: " + array[1]);
}
}
Arrays.sort()
sorts the strings for you. Taking the second (index 1) string out of the sorted array gives you the middle string. If you want to sort using case-insensitive ordering, you can use Arrays.sort(array, String.CASE_INSENSITIVE_ORDER)
.