I have a program which has the user inputs a list of names. I have a switch case going to a function which I would like to have the names print off in alphabetical order.
public static void orderedGuests(String[] hotel) { //?? }
I have tried both
Arrays.sort(hotel); System.out.println(Arrays.toString(hotel));
and
java.util.Collections.sort(hotel);
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.
To sort an array of strings in Java, we can use Arrays. sort() function.
To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.
Weird, your code seems to work for me:
import java.util.Arrays; public class Test { public static void main(String[] args) { // args is the list of guests Arrays.sort(args); for(int i = 0; i < args.length; i++) System.out.println(args[i]); } }
I ran that code using "java Test Bobby Joe Angel" and here is the output:
$ java Test Bobby Joe Angel Angel Bobby Joe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With