Reputation: 729
OK, here is my problem. I need to take a array of Strings and sort it alphabetically and then print out the first String: For example, a string of "Georgia, Florida, Alabama", It should print out Alabama. The Strings are not submitted by the user, i have a file with a bunch of states that is inputed as an array.
This is what I have:
import java.io.*;
import java.util.*;
public class MinString
{
private static final int SIZE = 10;
public static void main(String[] args)
{
String[] list = new String[SIZE];
int numItems;
numItems = Initialize (list);
System.out.println(numItems);
}
private static int Initialize (String[] list)
{
//post : List is initialized with all strings from file.
String filename, stateInput;
int i = 0, numItems = 0;
try {
System.out.print("Input File : ");
Scanner stdin = new Scanner(System.in);
filename = stdin.nextLine();
stdin = new Scanner(new File(filename));
while ((stdin.hasNext()) && (i < list.length))
{
stateInput = stdin.nextLine();
System.out.println("S = " + stateInput);
list[i] = stateInput;
i++;
}
numItems = i;
}
catch (IOException e) {
System.out.println(e.getMessage());
}
return numItems;
}
// Method FindMin goes here
private static String FindMin (String[] list, numItems);
?????
}
I'm not sure how to write this FindMin Method. I need to write FindMin so that it takes as input an array of size numItems of strings and returns to the calling function the minimum string.
Any ideas?
Upvotes: 0
Views: 4944
Reputation:
The simplest way to do it is:
return Collections.min(Arrays.asList(list));
Upvotes: 1
Reputation: 301
import java.util.*;
class Six
{
public static void main(String arg[])
{
String str[]=new String[5];
Scanner in=new Scanner(System.in);
System.out.println("Enter the element of array :");
for(int i=0;i<=4;i++)
{
str[i]=in.next();
}
Arrays.sort(str);
System.out.println("The first element after sorting is:");
System.out.println(str[0]);
}
}
Upvotes: 0
Reputation: 11075
just use Arrays.sort(list) and the list will get sorted.
Upvotes: 0
Reputation: 18
private static String findMin(String[] list) {
String minState = list[0];
for(int i=1; i<list.length; i++){
String min=list[i];
minState=(min!=null&&min.compareTo(minState)<0)?min:minState;
}
return minState;
}
Upvotes: -1
Reputation: 33029
The java.util.Arrays
object contains a bunch of static methods for working with arrays. I think Arrays.sort
would probably help you here. Since Strings implement the Comparable
interface with an alphabetic ordering the sorted array should give you the information you need.
Upvotes: 1
Reputation: 15628
Since this feels like a homework I will help you to help yourself:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#compareTo(java.lang.String)
Upvotes: 3