2017-01-25 102 views
1

我正在做一個分配,我需要從文件中讀取樣本輸入並將其插入到二維數組中。以下是一個輸入示例:讀取值插入二維數組

5 6 
1 3 4 B 4 3 
0 3 5 0 0 9 
0 5 3 5 0 2 
4 3 4 0 0 4 
0 2 9 S 2 1 

5和6是數組的維數。用戶必須能夠一次輸入許多像這樣的數組,當用戶輸入-1時程序結束。這是我迄今似乎並不奏效,因爲它應該(我打印出來的陣列,以確保代碼工作)代碼:

public static void main (String[] args){ 
    Scanner sc = new Scanner(System.in); 
    int arHeight = sc.nextInt(); 
    int arWidth = sc.nextInt(); 
    sc.useDelimiter(" "); 
    String[][] map = new String[arHeight][arWidth]; 

     for(int i=0; i<arHeight; i++){ 
      for(int j=0; j<arWidth; j++){ 
       map[i][j] = sc.nextLine(); 
      }//end inner for 
     }//end outter for 

      for(int i=0; i<arHeight; i++){ 
      for(int j=0; j<arWidth; j++){ 
       System.out.print(map[i][j] + " "); 
      }//end inner for 
     }//end outter for 
    } 

的分配狀態,我不能使用遞歸和我必須使用二維數組。我已經看過其他問題,但似乎無法弄清楚。 感謝您的幫助!

+0

歡迎來到Stack Overflow!看起來你正在尋求作業幫助。雖然我們本身沒有任何問題,但請觀察這些[應做和不應該](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),並相應地編輯您的問題。 –

+0

謝謝,我馬上就明白:) – Gabbie

回答

2

你讀了整條生產線我*進行j次

for(int i=0; i<arHeight; i++){ 
     for(int j=0; j<arWidth; j++){ 
      map[i][j] = sc.nextLine(); 

也是你保持人在一個字符串數組中的數據,我不知道爲什麼。這裏是解決方案:

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    int arHeight = sc.nextInt(); 
    int arWidth = sc.nextInt(); 

    int[][] map = new int[arHeight][arWidth]; 

    for(int i=0; i<arHeight; i++){ 
     for(int j=0; j<arWidth; j++){ 
      map[i][j] = sc.nextInt(); 
     }//end inner for 
    }//end outter for 

    for(int i=0; i<arHeight; i++){ 
     for(int j=0; j<arWidth; j++){ 
      System.out.print(map[i][j] + " "); 
     }//end inner for 
    } 

} 

然後嘗試使用

char[][] map = new char[arHeight][arWidth]; 

,並在for循環:

if(sc.next().charAt(0) != " ") map[i][j] =sc.next().charAt(0); 

這樣,你應該閱讀所有這些都沒有的 「字符」。

+0

我曾經使用過一個字符串數組,因爲數組中有兩個字符,B和S.會不會有一個字符數組最好? – Gabbie

+0

我會更新答案。我沒有注意到你有字符 –

+0

謝謝,我感謝幫助!它現在似乎正在工作! – Gabbie