How to Fix Errors in Alphabetically Sorting Full Names in Java?

  • Context: Java 
  • Thread starter Thread starter sunbuster
  • Start date Start date
  • Tags Tags
    Sort
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
sunbuster
Messages
10
Reaction score
0
Code:
import javax.swing.*;
import java.util.Arrays;

public class sortSelection
{
	public static void main(String args[])
	{
		String inputString;
		char temp;
		
		inputString = JOptionPane.showInputDialog("Enter Your Name");
		
		char a = inputString.charAt(0);
		char b = inputString.charAt(1);
		char c = inputString.charAt(2);
		char d = inputString.charAt(3);
		char e = inputString.charAt(4);
		char f = inputString.charAt(5);
		char g = inputString.charAt(6);
		char h = inputString.charAt(7);
		char k = inputString.charAt(8);
		char l = inputString.charAt(9);
		char m = inputString.charAt(10);
		char n = inputString.charAt(11);
		char o = inputString.charAt(12);
		char p = inputString.charAt(13);
		char q = inputString.charAt(14);


		char[] fullName = {a, b, c, d, e, f, g, h, k, l, m, n, o, p, q};
		
		for(int i=0; i<fullName.length -1; i++)
			for(int j=0; j<fullName.length -1; j++)
			{
			if(fullName[j]>(fullName[j+1]))
				{
					temp = fullName[j];
					fullName[j] = fullName[j+1];
					fullName[j+1] = temp;
				}
			}		
		System.out.print(fullName[0]);
		System.out.print(fullName[1]);
		System.out.print(fullName[2]);
		System.out.print(fullName[3]);
		System.out.print(fullName[4]);
		System.out.print(fullName[5]);
		System.out.print(fullName[6]);
		System.out.print(fullName[7]);
		System.out.print(fullName[8]);
		System.out.print(fullName[9]);
		System.out.print(fullName[10]);
		System.out.print(fullName[11]);
		System.out.print(fullName[12]);
		System.out.print(fullName[13]);
		System.out.print(fullName[14]);
		
		}
}

=>>> Here is my code. It keeps make errors when I type the others name. What should I do?
 
Last edited by a moderator:
Physics news on Phys.org
That is, by far, the most convoluted way to turn a string into an array of chars that I have ever seen.

Are you trying to sort the characters in a String containing a name into alphabetical order? I'm wondering because I can't think of a reason anyone would ever want to do that. :smile:

First thing is to get that char array in a less painful way. Something like this would be preferable:

char[] fullName = inputString.toCharArray();

That will also work with strings of any length. There's documentation for the String class and the rest here, and I suggest you use it:

http://download.oracle.com/javase/6/docs/api/index.html

You'll also want to print it out after in a bit of a better way. At least use a for loop.