2013-04-18 59 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]); 
      } 
     } 
    } 
} 

口口聲聲說:

異常線程「main」 java.lang.NullPointerExcept MultTable.fillRows(MultTable.java:41)在MultTable.main(MultTable.java:13)

回答

0

這個代碼有幾個問題。首先,您得到的例外是因爲rows在您嘗試訪問fillRows()中的length時爲空。

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

這是因爲當getRows()使用int rows[]=new int[sizerow];,它初始化一個新的局部變量,只對getRows()功能可見。您可能需要改爲rows = new int[sizerow];。這將初始化上面聲明的成員變量。同樣對於cols。

fillRows()fillCols()的循環中正在進行類似的不正確分配。對於那些,你可能想要做一些像rows[i] = i + 1;而不是。

此外,請仔細檢查所有循環上的邊界。其中一些從1開始,一些爲0.其中一些使用<= length,一些< length。您可能要從0開始,並在所有這些上使用< length

+0

謝謝!這是小事情..... – user2209838