2013-10-28 39 views
0

該程序符合,但我不能打印出結果表。該程序應該分析1和0的隨機表格,並打印出一張表,按順序計算該數字爲1。表格大小由用戶創建的輸入生成。這工作正常,但我無法打印結果表。我感謝一種不同類型的隨機工具可能會起作用。該程序將編譯,但表格將不會打印

現在我只是得到一個表全是零....

import java.util.Scanner; 
import java.util.Random; 

public class Project1a { 
    static int[][] results; 
    static int[][] sample; 

    static int goodData = 1; 

    public static void main(String[] args) { // main comes first (or last) 
     scanInfo(); 
     analyzeTable(); 
     printTable(results); 

    } 


    public static void scanInfo() 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter number of rows: "); 
     int rows = input.nextInt(); 
     System.out.println("Enter number of columns: "); 
     int columns = input.nextInt(); 
     Random randomNumbers = new Random(); 
     sample = new int[rows= randomNumbers.nextInt(50)][columns = randomNumbers.nextInt(50)]; 
     results = new int[rows][columns]; 


    } 



    static void analyzeTable() { // no argument. static var sample is assumed 
     int row=0; 
     while (row < sample.length) { 
      analyzeRow(row); 
      row++; 
     } 
    } 
    static void analyzeRow(int row) { // assume sample is "global" 
     int xCol = 0; 
     int rCount = 0; 
     while (xCol < sample[row].length) { 
      rCount = analyzeCell(row,xCol); 
      results[row][xCol] = rCount; // instead of print 
      xCol++; 
     } 
    } 
    static int analyzeCell(int row, int col) { 
     int xCol = col; 
     int runCount = 0; 
     int rowLen = sample[row].length; 
     int hereData = sample[row][xCol]; 
     while (hereData == goodData && xCol < rowLen) { 
      runCount++; 
      xCol++; 
      if (xCol < rowLen) { hereData = sample[row][xCol];} 
     } 
     return runCount; 
    } 

    public static void printTable(int[][] aTable) { 
    for (int[] row : aTable) { 

     printRow(row); 
     System.out.println(); 
    } 
    } 
    public static void printRow(int[] aRow) { 
    for (int cell : aRow) { 
     System.out.printf("%d ", cell); 
    } 
    } 
} 

回答

1

您的問題是這條線。

sample = new int[rows= randomNumbers.nextInt(1)][columns = randomNumbers.nextInt(2)]; 

你看,nextInt(1)總是會返回0,所以你設置rows爲零,而你最終得到一對數組有沒有行的。

從的Javadoc nextInt -

public int nextInt(int n)

返回一個僞隨機,均勻地介於0(含) 分佈的int值和指定的值 (不含),從該隨機數生成器的吸入序列。