2012-03-07 5 views
1

에 스캐너를 사용하여 텍스트 파일에서 읽기. 스캐너에는 nextChar 메서드가 없으므로 next()를 사용하고 해당 행을 문자로 분할한다고 가정합니다. 나는 문자열을위한 것, 행을위한 것 그리고 열을위한 것 중 하나를 위해 3 for 루프를 사용하는 것에 매달렸다. 여기자바 - 나는 30x30의 문자 배열에 텍스트 파일을 읽기 위해 노력하고있어 2 차원 문자 배열

내 코드 원경이다 ..

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); 

이제 I 어레이 행 & 컬럼 문에 2 할 것이다하고 chargrid 예 [I] [J] = testchar 설정?

도움을 주시면 감사하겠습니다.

+0

왜 당신은 30x30의 문자로 텍스트 파일을 읽으려는 좋은가 무엇인지에 대한

을 알려주세요 배열과 왜 단순히'List '에 들어 가지 않을까요? 내가 정말하고 싶었던 무엇 – anubhava

+0

는 숯불 = 'X'그 셀은 사실이 될 것입니다 경우 30x30 부울 배열을 가지고,하지만 난 말할 것도 그렇게, 그것은 배열 오른쪽에 텍스트 파일을 읽을 수 없습니다 . 내가 제안이 경우 – josh

+0

먼저'목록 '에서 파일을 읽고 다음 30x30 부울 배열을 채 웁니다이'목록 을'검사합니다. – anubhava

답변

0

까지 내가 당신의 코멘트에서 본대로 캐릭터가 내 코드에서 두 배열 작성 그래서 'X'의 경우도 부울과 2 차원 배열을 가지고 싶습니다 - true 또는 false로 실제로 문자 하나 하나를 , 문자에 따라 'X'또는 아닙니다. 또한 작동 원리를 더 잘 이해할 수있는 system.outs도 있습니다. 나타나는 때 나는 ('\ n')에 개행 문자를 제거하고 BTW

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(); 
    } 

(해당 여부를 원한다면 잘 모릅니다). 내가 대신 스캐너를 사용하는 InputStream로부터 문자에 대한 문자를 읽고있다는 괜찮 희망 - 그렇지 않으면 내가 지금이