how to sort names using compareto
i have this problem with my code.
it need to put three names in alphabetical order that are entered from the user. then output the alphabetical result. the program compiles but when you put in different names there are not alphabeticals. i think only the first if works good. any help would be appreciated.
Code java:
import javax.swing.JOptionPane;
public class Sort
{
public static void main(String[] args)
{
String name1;
String name2;
String name3;
name1 = JOptionPane.showInputDialog(null, "Enter a name");
name2 = JOptionPane.showInputDialog(null, "Enter second name");
name3 = JOptionPane.showInputDialog(null, "Enter third name");
if (name1.compareTo(name2) < 0)
{
if (name2.compareTo(name3) < 0)
{
JOptionPane.showMessageDialog(null, "Alphabetical order: \n"
+ name1 + "," + name2 + "," + name3);
}
else
{
JOptionPane.showMessageDialog(null, "Alphabetical order: \n"
+ name1 + "," + name3 + "," + name2);
}
}
else if (name2.compareTo(name1) < 0)
{
if (name1.compareTo(name3) < 0)
{
JOptionPane.showMessageDialog(null, "Alphabetical order: \n"
+ name2 + "," + name1 + "," + name3);
}
else
{
JOptionPane.showMessageDialog(null, "Alphabetical order: \n"
+ name2 + "," + name3 + "," + name1);
}
}
else if (name3.compareTo(name1) < 0)
{
if (name1.compareTo(name2) < 0)
{
JOptionPane.showMessageDialog(null, "Alphabetical order: \n"
+ name3 + "," + name1 + "," + name2);
}
else
{
JOptionPane.showMessageDialog(null, "Alphabetical order: \n"
+ name3 + "," + name2 + ","+ name1);
}
}
}
}
Re: how to sort names using compareto
i would add names to array compare index 1 with 0 and ind index 2 with 1(array[i] with array[i-1]) and swap the words if not correctly position
(bubblesort)
Re: how to sort names using compareto
i can only use compareto as that is where my class is currently are and im a beginner. i cant seem to find the error in my if statements any help
Re: how to sort names using compareto
Quote:
Originally Posted by
kittykat0953
i cant seem to find the error in my if statements any help
The error is in the concept of ifs structure.
Get for example the first block, which conceptually (pseudo code) means:
Code :
IF name1 < name2 THEN
IF name2 < name3 THEN
sequence is name1 , name2 , name3
ELSE
sequence is name1 , name3 , name2
ENDIF
ENDIF
Given:
name1="B"
name2="F"
name3="A"
the first IF is true. The second IF is false. But this does not mean that the sequence is name1 , name3 , name2 (B A F)!
You have to restructure and add if statements.