2012-03-07 56 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而不是使用扫描仪的性格,希望是好的 - 否则让我知道

对什么都这会是个不错