如何将设置的数组大小更改为用户选择的随机大小的数组。
以下是设置大小数组的设置。我只是不知道如何转换为随机大小....
import java.util.Scanner;
public class Project1a {
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();
int[][] nums = new int[rows][columns];
static int[][] sample = nums;
}
static int[][] results = new int[4][5];
static int goodData = 1;
public static void main(String[] args) {
analyzeTable();
printTable(results);
}
static void analyzeTable() {
int row=0;
while (row < sample.length) {
analyzeRow(row);
row++;
}
}
static void analyzeRow(int row) {
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; // varies in the loop
int runCount = 0; // initialize counter
int rowLen = sample[row].length; // shorthand
int hereData = sample[row][xCol]; // shorthand
while (hereData == goodData && xCol < rowLen) {
runCount++;
xCol++;
if (xCol < rowLen) { hereData = sample[row][xCol];}
}
return runCount;
}
/* Start Print Stuff */
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);
}
}
}
/* End Print Stuff */
我现在只在第18行收到一个错误:非法开始表达。我认为我没有正确定义变量。
答案 0 :(得分:0)
您可以重新编写代码以使用ArrayList
:
import java.util.ArrayList;
//Here you create an 'array' that will contain 'arrays' of int values
ArrayList<ArrayList<Integer>> sample = new ArrayList<ArrayList<Integer>>();
然后添加每一行:
sample.add(new ArrayList<Integer>());
并向行添加元素:
sample.get(0).add(5); // get(0) because is the first row, and 5 is int
当然,您必须修改代码才能使用这种数组。
答案 1 :(得分:0)
尽管在处理多维数组时它变得复杂,但您无法在Java中更改数组大小。我建议您熟悉Java Array docs。
您可以做的是创建一个所需大小的新数组,然后将旧数组中的数据复制到新数组中。
答案 2 :(得分:0)
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: "); // get number of rows
int rows = input.nextInt();
System.out.println("Enter number of columns: "); // get number of columns
int columns = input.nextInt();;
int[][] nums = new int[rows][columns]; // new 2D array, randomly
// sized by user input
这就是你要找的全部吗?基于你的问题,这就是它的样子
如果您希望方法使用随机1
和0
填充它,请执行此操作
static void populate(int[][] nums) {
for (int i = 0; i < row.length; i++) {
for (int j = 0; j < column.length; i++) {
nums[row][column] = (int)(Math.random() + 1);
}
}
}
现在num
是一个包含随机1
和0
的