我正在嘗試編寫一個程序,要求用戶在每行輸入一個n
字,並將輸出結果作爲字典排序的字。編輯用戶輸入no。lexicograhical順序的java代碼。字
它要求用戶輸入第一行的字數,然後在每行輸入一個字。我應該爲這個程序使用一個多維數組。
我的代碼可以正常工作,但它無法將n
字數作爲用戶輸入的字數,而是僅佔用n - 1
個字。
public static void main (String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String arr[] = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = input.nextLine();
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i].compareTo(arr[j])>0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < n; i++)
System.out.println(arr[i]);
}
請寄出你回來的錯誤,以及你試圖解決的問題。乾杯 – Alos
'nextLine()'在返回用戶輸入後自動下移。 –
@Niraj非常感謝你指出'nextLine()'這是我的程序錯誤的根源。用next()代替它解決了這個問題。然後,我可以輸入所需的'n'個字作爲用戶輸入。 –