This program is supposed to take the array of command line arguments and sort them alphabetically. Problem is I'm getting an ArrayOutOfBoundsException somewhere. I also have a problem with the while loop. The way I've decided to alphabetize the array with looks a little bit shoddy. My plan was to examine the array in pairs, and keep swapping args.length*2 times until it was done.
ie.
bcda <-original
bcad <-swapped back once
bacd <-twice
abcd <-done

However I dont feel like that will work for all cases. Does anyone have a better was of doing this? I am a beginner so I only have a "beginner toolkit" to work with.

public class AlphaB2 {

    public static void main(String[] args) {
    	
    	int count = 0;
    	while(count < (args.length * 2)){
    	   	for(int i=0;i<args.length;i++){
    			if(args[i].compareToIgnoreCase(args[i+1])<0){ //if first is after second
    				String temp1 = args[i];
    				String temp2 = args[i+1];
    				args[i] = temp1;
    				args[i+1] = temp2;
    			}
    		}//end for
    	count++;
    	}//end while
    }//end main
}//end class

The out of bounds is simple enough. You're going to i<args.length, which is correct. But then in the loop, you're addressing args[i++] - this means you're addressing args[length] in the last time through. That address doesn't exist, so there's your outofboundsexception.

The sort you're describing is more or less a bubble sort, but it needs a little work. There's plenty of information out there on implementing this, so mostly my advice is "ask google".
That being said, think about the logic of the thing. You're advancing through the array from bottom to top, and if item i and its neighbor are out of order, you're swapping them. Pull some coins out of your pocket, take four of them with different values, and try going through that sequence with different starting orders.
I think you're going to find that you need an inner loop to get this done.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.