0
這是一個基本名稱排序程序。除了用戶不能輸入名字這一事實以外,一切都有效。這是代碼:掃描儀跳過循環中的第一個輸入Java
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] + " ");
}
}
更新:我改變了代碼,所以如果它是第一次時,它調用sc.nextLine(),然後將輸入等於名稱[0] 一個問題的.next ()是,如果一個人的名字是兩個單詞將其視爲兩個名字。這是更新的代碼工作:
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] + " ");
}
}
你有你的答案,如果沒有的話,請寫你的答案,這樣其他的可以從中受益。 stackoverflow.com/help/accepted-answer – hagrawal