2014-09-18 68 views
3
package com.test; 
import java.util.Scanner; 

public class Main { 

    public static void main(String args[]) { 
     System.out.println("Rows = ?"); 
     Scanner sc = new Scanner(System.in); 
     if(sc.hasNextInt()) { 
      int nrows = sc.nextInt(); 
      System.out.println("Columns = ?"); 
      if(sc.hasNextInt()) { 
       int ncolumns = sc.nextInt(); 
       char matrix[][] = new char[nrows][ncolumns]; 
       System.out.println("Enter matrix"); 
       for (int row = 0; sc.hasNextLine() && nrows > row; row++) { 
         matrix[row] = sc.nextLine().toCharArray(); 
       } 
       for (int row = 0; row < nrows; row++) { 
        for (int column = 0; column < matrix[row].length; column++) { 
         System.out.print(matrix[row][column] + "\t"); 
        } 
        System.out.println(); 
       } 
      } 
     } 
    } 
} 

所以我的程序讀取矩陣並打印它,但最後一行不打印。我認爲,for循環中的問題是打印列。Java Matrix不打印最後一行

輸入:

2 
2 
-= 
=- 

實際輸出:

-= 

預期輸出:

-= 
=- 
+0

您可以發佈輸入,實際輸出和預期輸出嗎?這可能是因爲你沒有在第一個for循環中正確地填充你的變量。 – 2014-09-18 19:00:31

+0

你確定這段代碼是'matrix [row] = sc.nextLine()。toCharArray();'做了你想要的嗎?你想在這裏做什麼? – Pshemo 2014-09-18 19:00:41

+0

@Pshemo yeap,我敢肯定 – underline 2014-09-18 19:01:44

回答

3

您需要更改

for (int row = 0; sc.hasNextLine() && nrows > row; row++) { 
     matrix[row] = sc.nextLine().toCharArray(); 
} 

sc.nextLine(); 
for (int row = 0; nrows > row; row++) { 
     matrix[row] = sc.nextLine().toCharArray(); 
} 

主要問題是nextInt()或其他nextXXX()方法除了nextLine()不消耗行分隔符,這意味着當你輸入2(然後按回車)實際投入的樣子2\n2\r\n2\r取決於操作系統。

因此,與nextInt你正在閱讀的唯一價值2但掃描儀的光標會前行分隔符像

2|\r\n 
^-----cursor 

這將使nextLine()返回空字符串,因爲潔具光標和下一行分隔符之間沒有任何字符集。

所以要實際讀取nextInt(不是空字符串)之後的行,您需要添加另一個nextLine()以在這些行分隔符之後設置光標。

2\r\n| 
    ^-----cursor - nextLine() will return characters from here 
        till next line separators or end of stream 

BTW避免這個問題,你可以使用

int i = Integer.parseInt(sc.nextLine()); 

代替int i = nextInt()

+0

nextInt()不會消耗換行符,你需要nextLine來做到這一點。 – folkol 2014-09-18 19:15:15