Reputation: 307
I'm trying to sort a list of strings in array into alphabetical order without using the sort method.
public static String[] sortedAdjectives(String[] original)
{
String[] sortedArray;
int aValue = 65;
String word = "";
sortedArray = new String[25];
for(int i = 0; i <25; i++)
{
original[i]=word;
char c = word.charAt(0);
sortedArray[c-aValue]=word;
}
return sortedArray;
Is my method, and
public static void main(String[] args) throws FileNotFoundException {
Scanner names = new Scanner(new File("names.txt"));
Scanner adjectives = new Scanner(new File("adjectives.txt"));
String[] adjectiveArray;
adjectiveArray = new String[25];
int counter = 0;
while (counter<25)
{
String in = adjectives.next();
fixCapitalization(in); //method that fixes capitalization
adjectiveArray[counter]=in;
counter++;
}
sortedAdjectives(adjectiveArray);
Is where I put the items from the file into an array. I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Hmwk.sortedAdjectives(Hmwk.java:56)
at Hmwk.main(Hmwk.java:24)
When I try to run my program and I can't figure out where I'm going wrong. If you could point me in the right direction i'd be much appreciative. Thanks for your time.
Upvotes: 0
Views: 131
Reputation: 5
You made a little mistake in the for loop. It should probably be word = original[i]; which you did it inversely and makes the word never take the original parameter as reference.
Also a few things to improve here: using arraylist would have better extensibility and avoid erasing repetitive letters.
Upvotes: 0
Reputation: 4636
You have word
initialized as an empty string:
String word = "";
Then you are calling charAt(0)
on an empty string. Can't do that.
Your string needs to be at least longer than 1 character in order to call that method.
Upvotes: 3