2011-11-08 3 views
0

프로그래밍에 익숙하지 않아 평신도의 말에 감사드립니다.파일의 내용을 2D 배열로 읽어들입니다.

9 개의 값 (3x3 배열)을 포함하는 파일 내용을 읽고 해당 내용을 해당 색인에 배치해야한다는 과제가 있습니다. 컨텐츠가 판독 된 후 예를 들어

,

차원 어레이의 내용은 ...

1.00 -2.00 3.00 
4.00 1.00 -1.00 
1.00 2.00 1.00 

, 그들은 인쇄 할 필요가있다. 그러면 프로그램은 사용자에게 '4'와 같은 스칼라 승수를 묻습니다. 그런 다음 프로그램은 새 출력을 사용하여 새 배열을 인쇄해야합니다. 나는 현재이이

,

import java.io.*; 
import java.util.*; 


public class CS240Lab8a { 

/** 
* @param args the command line arguments 
*/ 
static double [][] matrix = new double[3][3]; 
static Scanner input = new Scanner(System.in); 


public static void main(String[] args) throws IOException 
{ 
    // Variables 
    String fileName = "ArrayValues.txt"; 




    // print description 
    printDescription(); 

    // read the file 
    readFile(fileName); 

    // print the matrix 
    printArray(fileName, matrix); 

    // multiply the matrix 
    multiplyArray(fileName, matrix); 


} 


// Program Description 
     public static void printDescription() 
     { 
      System.out.println("Your program is to read data from a file named ArrayValues.txt and store the values in a 2D 3 X 3 array. " 
        + "\nNext your program is to ask the user for a scalar multiplier \n" 
        + "which is then used to multiply each element of the 2D 3 X 3 array.\n\n"); 
     } 



// Read File 
     public static void readFile(String fileName) throws IOException 
     { 
      String line = ""; 

      FileInputStream inputStream = new FileInputStream(fileName); 
      Scanner scanner = new Scanner(inputStream); 
      DataInputStream in = new DataInputStream(inputStream); 
      BufferedReader bf = new BufferedReader(new InputStreamReader(in)); 

      int lineCount = 0; 
      String[] numbers; 
      while ((line = bf.readLine()) != null) 
      { 
       numbers = line.split(" "); 
       for (int i = 0; i < 3; i++) 
       { 
       matrix[lineCount][i] = Double.parseDouble(numbers[i]); 
       } 

       lineCount++; 
      } 
      bf.close(); 

     } 


// Print Array  
     public static void printArray(String fileName, double [][] array) 
     { 
      System.out.println("The matrix is:"); 

      for (int i = 0; i < 3; i++) 
       { 
        for(int j = 0; j < 3; j++) 
        { 
         System.out.print(matrix[i][j] + " "); 
        } 
        System.out.println(); 
       } 
      System.out.println(); 
     } 

     public static double multiplyArray(String fileName, double[][] matrix) 
     { 
       double multiply = 0; 

       System.out.println("Please enter the scalar multiplier to be used."); 
       multiply = input.nextDouble(); 

       for(int i = 0; i < 3; i++) 
       { 
        for(int j = 0; j < 3; j++) 
        { 
         matrix[i][j] 

       return multiply; 
      } 



} // end of class 

나는 현재 제대로 배열을 인쇄 할 수 있습니다.

모든 색인 값에 상수 (사용자 입력)를 곱하는 가장 좋은 방법은 무엇입니까?

+0

첫 번째 문제점은 매트릭스에 아무 것도 지정하지 않았다는 것입니다. 실제로 readFile 메서드 내에 matrix라는 새로운 2 차원 배열을 만듭니다. 두 번째 문제는 readFile 메소드에서 matrix [0] [0] = numbers; 루프에서 ... 행렬의 첫 번째 위치에만 값을 할당합니다. –

+0

* "첫 번째 줄을 수락하지만 후에 실패합니다."* 어떻게 실패합니까? 구체적으로 말하십시오. BTW - 질문 있니? –

+0

aleph_null - 'double'= (x, y) index와 같이 각 'double'을 인덱스에 저장하는 방법에 대한 제안이 있습니까? 또한 사전 소송을 제기 한 후 다음 색인으로 어떻게 넘어갈 수 있습니까? – fisherml

답변

2

여기에 추가 단계가 없습니다.

일단 줄을 읽으면 개별 줄에 줄과 parseDouble을 나누어야합니다.

또한 readFile은 아무 것도 반환하지 않아도됩니다. 행렬 변수를 전역 변수로 만드십시오.

+0

칼,이 도움이되었습니다. 그러나 결과는 이제"매트릭스는 : 0.00.00.00.00.00.00.00.00.0 "입니다. – fisherml

+0

printArray 안에 새로운 변수'matrix'가 선언되었습니다. m ethod .. 선언을 제거하고'matrix' 변수를 전역 변수로 만드십시오. 클래스 정의 내부의 맨 위에서 선언하십시오. – Kal

+0

나는이 잘 작동 지금 배열의 곱하기 이동합니다. – fisherml

0

좋아, 내가보기에 : 문자열로 입력 파일의 내용을 읽습니다. 이미 한 줄씩 읽는 방법은 모든 것을 문자열에 넣는 것입니다.

String content = readFile(input.txt); 

// Parse lines 

String[] lines = content.split("\n"); 

// Parses values 

for(int i = 0; i < lines.length; i++) { 
    // Get line values 
    String[] values = lines[i].split(" "); 
    for(int j = 0; j < values.length; j++) { 
     // Punt in Matrix 
     matrix[i][j] = Double.parseDouble(values[j]); 
    } 
} 
+0

Heineken, 1) 기본 메서드에서 'String content = readFile (input.txt)'을 사용하고 있습니까? 그렇다면 문자열로 readFile을 저장하려했지만 readFile이 void 메서드이므로 '호환되지 않는 유형'을 제공합니다. 그렇지 않으면 'readFile'메소드에서 'readFile'을 어떻게 호출합니까? – fisherml

+0

ideia는 readFile을 수정하여 파일 내용이있는 문자열을 반환했습니다. 쉽습니다 : P – Gabriel

관련 문제