This is a basic name sorting program. Everything works except for the fact that the user cannot input the first name. This is the code:
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
for (int x = 0; x < names.length; x++){
int pos = x+1;
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++){
System.out.print(sortedArray[i] + " ");
}
}
Update: I changed the code so if it is the first time, it calls sc.nextLine() and then sets the input equal to names[0] One problem with .next() is that if a person's first name is 2 words to treats it as two names. This is the updated code that works:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
//String[] temp = new String[names.length];
for (int x = 0; x < names.length; x++) {
int pos = x + 1;
if (x == 0) {
System.out.println("Enter name 1");
sc.nextLine();
names[0] = sc.nextLine();
} else {
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++) {
System.out.print(sortedArray[i] + " ");
}
}