2012-03-07 70 views
1

我想讀取文本文件轉換成30×30字符數組從文本文件中讀取。掃描儀沒有nextChar方法,所以我假設我將使用next(),然後將該行分割爲字符?我掛斷了使用3 for循環來做到這一點,但一個用於字符串,一個用於行,一個用於列。爪哇 - 使用掃描成二維字符數組

這是到目前爲止我的代碼..

public static void main(String[] args) throws FileNotFoundException { 
    final int cellSize = 30; // grid size 
    char[][] chargrid = new char[cellSize][cellSize]; 
    File inputFile = new File("E:\\workspace\\Life2\\bin\\Sample input.txt"); 
    Scanner in = new Scanner(inputFile); 

    char testchar; 
    while(in.hasNext()){ 
    String s = in.next(); 
    for (int i=0; i<s.length();i++){ 
    testchar = s.charAt(i); 

現在我會爲矩陣行&列報表做2,然後設置chargrid [i] [j] =例如testchar?

任何幫助,將不勝感激。

+0

爲什麼你想讀取文本文件轉換成30×30字符數組,爲什麼不簡單地進入'List '? – anubhava 2012-03-07 17:11:53

+0

我真正想要做的是有一個30x30的布爾數組,如果char ='X',那麼這個單元格將是真實的,但我甚至不能將它讀入數組右邊的文本文件,更不用說做。 – josh 2012-03-07 17:15:23

+0

在這種情況下,我建議在'名單'先讀取該文件,然後檢查這個名單''來填充30×30布爾數組。 – anubhava 2012-03-07 17:57:47

回答

0

據我在您的評論看見你還想與布爾的二維數組,如果字符是「X」,所以我充滿在我的代碼兩個數組 - 一個實際與字符和一個與真或假,這取決於字符是'X'還是不是。還有一些system.out可以更好地理解它是如何工作的。我正在刪除換行符('\ n')出現時(不知道您是否想要)

public static void main(String[] args) { 
    final int cellSize = 30; // grid size 
    char[][] chargrid = new char[cellSize][cellSize]; 
    boolean[][] chargridIsX = new boolean[cellSize][cellSize]; 
    File inputFile = new File("input.txt"); 
    FileInputStream is = null; 
    try { 
     is = new FileInputStream(inputFile); 
     int n = -1; 
     int rowCount = 0; 
     int colCount = 0; 
     while((n=is.read()) !=-1){ 
      char readChar = (char) n; 
      if(readChar!='\n'){//This removes the linebreaks - dont know if you want that 
       chargrid[rowCount][colCount] = readChar; 
       if(readChar=='X') { // Here actually set true or false if character is 'X' 
        chargridIsX[rowCount][colCount] = true; 
        System.out.println("row "+rowCount+" col "+colCount + " = " + readChar + " " + true); 
       }else { 
        chargridIsX[rowCount][colCount] = false; 
        System.out.println("row "+rowCount+" col "+colCount + " = " + readChar+ " " + false); 
       } 
       if(rowCount++ >= cellSize-1){ 
        System.out.println("new col"); 
        rowCount = 0; 
        if(colCount++ >= cellSize-1){ 
         //ARRAY IS FULL 
         System.out.println("full"); 
         break; 
        } 
       } 
      } 
     } 

    } catch (FileNotFoundException e) { 
     //could not get Inputstream from file 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // problem with the inputstream while reading 
     e.printStackTrace(); 
    } 

btw。我讀字符從InputStream而不是使用掃描儀的性格,希望是好的 - 否則讓我知道

對什麼都這會是個不錯