2013-04-18 1 views
1

내가 사용자의 입력 배열의 크기를 지정하고 번호 1-크기를 배열을 추가 한 다음 열 배열을 인쇄하려고어떻게이 배열 곱셈 테이블이 일을 어떻게해야합니까

곱셈 테이블 할당 행하지만 난 꽤 괜찮 이런 짓을했는지 생각하지 않는다 :

import java.util.Scanner; 

public class MultTable 
{ 
    public static int[]rows; 
    public static int[]cols; 

    public static void main (String args[]) 
    { 
     intro(); 
     getRows(); 
     getCols(); 
     fillRows(); 
     fillCols(); 
     printTable(); 
    } 

    public static void intro() 
    { 
     System.out.print("Welcome to the Multiplication Table program!"); 
    } 

    public static void getRows() 
    { 
     Scanner input=new Scanner (System.in); 
     System.out.print("\nEnter number of row:"); 
     int sizerow=input.nextInt(); 
     int rows[]=new int[sizerow]; 
    } 

    public static void getCols() 
    { 
     Scanner input=new Scanner(System.in); 
     System.out.print("Enter number of columns:"); 
     int sizecol=input.nextInt(); 
     int cols[]=new int[sizecol]; 
    } 

    public static void fillRows() 
    { 
     for(int i=1;i<=rows.length;i++) 
     { 
      int rows[]=new int[i]; 
     } 
    } 

    public static void fillCols() 
    { 
     for(int j=0;j<cols.length;j++) 
     { 
      int cols[]=new int[j]; 
     } 
    } 

    public static void printTable() 
    { 
     System.out.print("\n\nHere is your %dx%d multiplication table:"); 
     System.out.print(cols); 
     System.out.print("--------"); 
     for(int i=1; i<=rows.length;i++) 
     { 
      for(int j=1;j<=cols.length;j++) 
      { 
       System.out.print(rows[i]*cols[j]); 
      } 
     } 
    } 
} 

이 말을 계속 : 스레드에서

예외 "주"java.lang.NullPointerExcept multTable.main (MultTable.java:13)의 MultTable.fillRows (MultTable.java:41)

답변

0

이 코드에는 몇 가지 문제점이 있습니다. 먼저 lengthfillRows()에 액세스하려고 시도하면 rows이 null이므로 예외가 발생합니다.

for(int i=1;i<=rows.length;i++) 
       ^^^^ 

이것은 getRows() 함수 getRows()에 사용 int rows[]=new int[sizerow];, 그것을 새로운 로컬 변수를 초기화 할 때 때문에 만 볼 수있다. 대신 rows = new int[sizerow];을 사용하고 싶을 것입니다. 위에서 선언 한 멤버 변수가 초기화됩니다. 칼과 마찬가지로.

fillRows()fillCols()의 루프에서 비슷한 잘못된 지정이 수행되고 있습니다. 그러한 경우 아마도 rows[i] = i + 1;과 같은 것을하고 싶을 것입니다.

또한 모든 루프의 경계를 다시 확인하십시오. 그들 중 일부는 1에서 시작합니다. 일부는 <= length, 일부는 < length입니다. 0에서 시작하여 < length을 사용하고 싶을 것입니다.

+0

감사합니다. 그것은 작은 것들 ..... – user2209838