2016-11-23 59 views
0

我試圖導入與此類似從文件存儲整數二維數組

5 5 
1 1 
3 3 
1 1 1 1 1 
1 0 1 0 1 
1 0 1 0 1 
1 0 0 0 1 
1 1 1 1 1 

文件轉換成二維數組,但我有難的時候,這是我到目前爲止的代碼,它什麼也不做,有AREN」 t語法錯誤,所以我沒有得到任何錯誤,但一個空白的控制檯,我不知道我做錯了什麼。數組的大小是文件內的前兩個數字。

package main; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class oboroten { 
public static void main(String[] args) { 
    int x, y; 
    x = y = 0; 
    int[][] maze = new int[x][y]; 
    try { 
     Scanner reader = new Scanner(new File("C:\\Users\\User\\Desktop\\mazes\\input.txt")); 
     x = reader.nextInt(); 
     y = reader.nextInt(); 
     for (int i = 0; i < x; i++){ 
      for (int j = 0; j < y; j++){ 
       maze[i][j] = reader.nextInt(); 
       System.out.println(maze[i][j]); 
      } 
     }  
     reader.close(); 
    } catch (FileNotFoundException e1) { 
     System.out.println("Problem with the file"); 
     e1.printStackTrace(); 
    } 
}} 
+1

'INT [] [] =迷宮新INT [X] [Y]'你的數組的大小設置爲0。難怪爲什麼你沒有得到outofbounds錯誤 – XtremeBaumer

+1

因爲'爲(...我從來都不是真的。 – Gendarme

回答

0

你初始化你的數組的大小爲0.所以沒有什麼會在那裏addet。

您必須在之後初始化數組,然後讀取文件並獲取尺寸。 試試這個:

public static void main(String[] args) { 
    int x, y; 
    int[][] maze; 
    try { 
     Scanner reader = new Scanner(new File("C:\\Users\\User\\Desktop\\mazes\\input.txt")); 
     x=reader.nextInt(); 
     y=reader.nextInt(); 
     maze = new int[x][y]; 
     for (int i=0; i<x; i++){ 
      for (int j=0; j<y; j++){ 
       maze[i][j]=reader.nextInt(); 
       System.out.println(maze[i][j]); 
      } 
     }  
     reader.close(); 
    } catch (FileNotFoundException e1) { 
     System.out.println("Problem with the file"); 
     e1.printStackTrace(); 
    } 
} 
+0

如果reader.nextInt()返回0,x和y將保持爲0;即如果文件以0開頭0 – Eritrean

+0

爲什麼文件應該以'0 0'開頭? @Eritrean – Gendarme

+0

@Gendarme爲什麼不呢? – Eritrean