2017-01-23 36 views
0

我正在嘗試編寫一個程序,要求用戶在每行輸入一個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]); 
} 
+0

請寄出你回來的錯誤,以及你試圖解決的問題。乾杯 – Alos

+0

'nextLine()'在返回用戶輸入後自動下移。 –

+0

@Niraj非常感謝你指出'nextLine()'這是我的程序錯誤的根源。用next()代替它解決了這個問題。然後,我可以輸入所需的'n'個字作爲用戶輸入。 –

回答

1

您遇到的問題與掃描儀的nextInt()方法有關。它只會只有從輸入緩衝區中讀取整數,並將換行符留在緩衝區中第一行的末尾。

這意味着,您在此之後第一次致電nextLine()將讀取一個空字符串並消耗換行符。

一個簡單的解決方法是隻需在input.nextInt()和您的閱讀循環之間撥打input.nextLine()

+0

對不起。我一開始並不能理解錯誤的根源,但是在重新閱讀您的文章並在我的程序中實現它之後,我現在明白它是'nextInt()'創建一個空字符串並通過插入一個'nextLine()'在nextInt()之後和read-loop之前立即解決了空串問題。謝謝。 –

0

您可以簡單地要求用戶輸入單詞並讓程序決定單詞的數量。

  Scanner input = new Scanner(System.in); 
      System.out.println("Enter words:"); 
      String data = input.nextLine(); 
      String[] arr= data.split("\\s+"); //splits the word by space and stores the words in pieces 
// and then do the lexicographical operations here 
相關問題