我正在尝试创建一个填充了1-99随机数的方阵。 我已经设置了这个,但是超过7个维度的任何东西都会返回错误,我不确定原因。
每次我开始超过最大尺寸时,它会突破不同。
package matrix;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class Matrix {
static int dim;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String repeat="yes";
do
{if (dim<=25)
{//prompt user for dimensions, only need one number
System.out.println("Please enter the dimensions of the matrices. Enter one number that is greater or equal to 25.");
dim=sc.nextInt();
//all rows and columns are equal
matrices m1 = new matrices(dim);
m1.randomFill();
m1.printMatrix();
System.out.print("\n Would you like to repeat the program? (yes/no)");
repeat=sc.next();
}
else
{System.out.print("Invalid dimensions, pleasse enter a number greater or equal to 25.");
dim=sc.nextInt();
}
}
while (repeat.trim().equalsIgnoreCase("yes"));
}
}
public class pool {
//instance variables
private int size;
static int [] poolArray;
private Random ridx;
//constructors
public pool (int sz)
{size = sz;
poolArray = new int [sz];
ridx = new Random ();
}
//instance methods
public void fillPool ()
{for(int n=0; n<size; n++)
{poolArray [n]=n+1;
}
}
public int randomValue ()
{int idx = ridx.nextInt(size);
int rval = poolArray [idx];
size--;
poolArray [idx] = poolArray [size];
return (rval);
}
public static void main(String[] args) {
pool p1 = new pool (99);
{p1.fillPool ();}
System.out.println(poolArray[0]+", "+poolArray[25]+", "+poolArray[98]);
System.out.println(p1.randomValue());
}
}
public class matrices {
static int [][] m;
static int size;
static pool p1 = new pool (99);
{p1.fillPool ();}
static pool p2 = new pool (99);
{p1.fillPool ();}
matrices (int dimension)
{m=new int [dimension][dimension];
size=dimension;}
static void randomFill ()
{int i, j; // loop counters
for (i=0;i<size;i++)
{ for(j=0;j<size;j++)
m[i][j]=p1.randomValue();
}
}
static void printMatrix()
{ int i, j; // loop counters
for (i=0;i<size;i++)
{ for(j=0;j<size;j++)
System.out.print(m[i][j] + " ");
System.out.println("");
}
System.out.println("");
}
}
这是出现的错误:
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:300) at matrix.pool.randomValue(pool.java:34)
at matrix.matrices.randomFill(matrices.java:28) at matrix.Matrix.main(Matrix.java:30) Java
Result: 1
答案 0 :(得分:0)
请格式化您的代码!
但如果rids.nextInt(size)
size < 0
,则integer overflow
会抛出错误
如果你有一个> Integer.MAX_VALUE
,那么你就可以尝试存储一个整数{{1}},可能,由于溢出而产生负值。此行为因整数而异。