Problem with string.compareTo();
I've been having an issue with a lab that I'm doing for school and my professor specifically wants us to use the .compareTo() method for the following code:
Code :
import java.util.*;
public class lab20 {
static Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
String[] names = new String[20];
int size = 0;
System.out.print("Enter a name, last name first(Enter 'END' to quit): ");
String name = in.nextLine();
while (!name.equals("END") && names.length <= 20)
{
names[size] = name;
System.out.print("Enter another name: ");
name = in.nextLine();
size++;
}
for (int i = 0; i < size; i++)
System.out.println(names[i]);
sort(names, size);
System.out.println();
for (int i = 0; i <size; i++)
System.out.println(names[i]);
}
public static void sort (String[] names, int size)
{
int i = 0;
int minPos;
String temp;
for (i = 0; i < size; i++)
{
minPos = minimunPosition(names, i, size);
temp = names[i];
names[i] = names[minPos];
names[minPos] = temp;
}
}
public static int minimunPosition(String[] names, int i, int size)
{
int minPos = i;
int k;
for (k = i+1; k < size; k++)
{
if (names[k].compareTo(names[minPos]) == -1)
minPos = k;
}
return minPos;
}
}
The input that I'm doing is:
Strickland, Bobby
Anderson, Brett
Keefer, Chris
Whymer, Josh
END
the output is the same as above without the END, obviously. I've tried using 1 instead of -1 as the return value of compareTo() but it's stays the same. I've changed the if statement to (name[k].charAt(0) < name[minPos].charAt(0)) but my professor said he'd take off points because he specifically want's me to use the compareTo(). Any help is greatly appreciated.
Re: Problem with string.compareTo();
@purvesh: I haven't seen him assigning the array to a variable.
@Drasumok: Please provide the exact question you need help with? What is the actual input, what is the output? In case of errors or exceptions, post here the full exception trace to get help.
Re: Problem with string.compareTo();
When does compareTo() return a -1? Where does the API say that value is returned?
Re: Problem with string.compareTo();
Please mark this thread as solved if the problem is solved.
Re: Problem with string.compareTo();
Quote:
Originally Posted by
Mr.777
@purvesh: I haven't seen him assigning the array to a variable.
@Drasumok: Please provide the exact question you need help with? What is the actual input, what is the output? In case of errors or exceptions, post here the full exception trace to get help.
Below the code is where I put the input and output of the program, and setting the compareTo() < 0 fixed my problem