How to alphabetize a list in Java

Hey, guys. Can anybody help me out with this issue? The extra challenge of exercise 5: https://www.codecademy.com/courses/java-loops-and-arrays/articles/code-challenge-loops-involving-array-traversal
I need to take a grocery list and alphabetize it. I tried doing it by swapping the Strings, but it doesn’t seem to be working. This is my code:

public static String alphabetizes (String groceryList){
if (groceryList.length > 1) {
String lastGroceryItem = groceryList[0];
}
for (int i = 0; i < groceryList.length; i++){
if (lastGroceryItem.compareTo(groceryList[i]) < 0) {
lastGroceryItem = String temp1;
groceryList[i] = String temp2;
lastGroceryItem = temp2;
groceryList[i] = temp1;
}
return groceryList;
}
}

I’m getting this error message:
GroceryList.java:21: error: ‘;’ expected
lastGroceryItem = String temp1;
^
GroceryList.java:21: error: not a statement
lastGroceryItem = String temp1;
^
GroceryList.java:22: error: ‘;’ expected
groceryList[i] = String temp2;
^
GroceryList.java:22: error: not a statement
groceryList[i] = String temp2;
^
4 errors

Any help would be greatly appreciated.

type variableName = value;

I assume you would like to swap temp1 and temp2. So if you define a variable in Java, the type (in this case String) is placed at the beginning of the line, followed by the variable name (in this case temp1 & temp2)
So it should be

String temp1 = lastGroceryItem;
String temp2 = groceryList[i];

Also, you defined lastGroceryItem inside the condition, then attempted to retrieve the value outside of it. In case you are not familiar with the concept of scope, here’s a quick explain:
You define a scope with { }. The variable created in it is only accessable within the scope. Variables defined outside all existing scope are called Global Variables.
So define lastGroceryItem outside the condition, then change its value when groceryList.length > 1.

2 Likes

Thank you very much, Joshua! It works now.
Rafael