0
我想創建一個方陣,填充1-99的隨機數。 我已經設置了這個,但是超過7個維度的任何內容都會返回一個錯誤,而我不是確定爲什麼。用隨機數填充的NxN矩陣1-99
每次我開始使用最大尺寸時,它都會有所不同。
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
發佈錯誤。 – Radiodef
@radiodef 錯誤: 異常在線程 「主」 java.lang.IllegalArgumentException異常:n必須是正 \t在java.util.Random.nextInt(Random.java:300) \t在matrix.pool.randomValue(池的.java:34) \t在matrix.matrices.randomFill(matrices.java:28) \t在matrix.Matrix.main(Matrix.java:30) Java結果:1 – lizeth
我很抱歉,很明顯,我學習。我從我之前完成的作業(完美地完成作業)中拿到了游泳池班,然後我嘗試拿出遞減部分(原本是爲了避免重複數字),但是它仍然給我錯誤,所以我保留了它in。 – lizeth