该程序符合要求,但是我无法获取结果表进行打印。该程序应该分析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);
}
}
}
最佳答案
您的问题是这条线。
sample = new int[rows= randomNumbers.nextInt(1)][columns = randomNumbers.nextInt(2)];
您会看到,
nextInt(1)
始终返回0,因此将rows
设置为零,最后得到了几个完全没有行的数组。从Javadoc中的
nextInt
-public int nextInt(int n)
均匀地返回伪随机
在0(含)和指定值之间分配的int值
(不包括),从此随机数生成器的序列中得出。