gpt4 book ai didi

java - 程序可以编译,但表格不会打印出来

转载 作者:行者123 更新时间:2023-12-01 13:55:39 25 4
gpt4 key购买 nike

程序符合要求,但我无法打印结果表。该程序应该分析 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 设置为零,最终得到几个没有行的数组完全没有。

来自 nextInt 的 Javadoc -

public int nextInt(int n)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

关于java - 程序可以编译,但表格不会打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19647018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com