我对java相当陌生,所以这可能看起来是一个基本问题。我试图使用 random java.util 和 nextInt 在用户输入指定的范围内创建一个随机数,然后将其转换为字符,然后存储在数组中;
gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a');
但是,因为我希望 nextInt 使用用户输入,并且虽然我控制值的范围,但我猜测错误是因为 nextInt 认为 numberOfRegions 可能为 0 而引起的?
// Map Class
import java.util.Random;
public class map
{
// number of grid regions
private int numberOfRegions;
private boolean correctRegions = false
// grid constants
private int xCord = 13; // 13 so the -1 makes 12 for a 12x12 grid
private int yCord = 13;
// initiate grid
private int[][] gridCells = new int[xCord][yCord];
Random r = new Random();
map() { }
// ask for number of regions
public void regions()
{
keyboard qwerty = new keyboard(); // keyboard class
while(correctRegions = false)
{
System.out.print("Please enter the number of regions: ");
numberOfRegions = qwerty.readInt();
if(numberOfRegions < 2) // nothing less then 2 accepted
{
correctRegions = false;
}
else if(numberOfRegions > 4) // nothing greater then 4 accepted
{
correctRegions = false;
}
else
{
correctRegions = true;
}
}
}
// fills the grid with regions
public void populateGrid()
{
for(int x =0; x<gridCells[x].length-1; x++) // -1 to avoid outofboundsexception error
{
for(int y =0; y<gridCells[y].length-1; y++)
{
gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a');
}
}
}
public void showGrid()
{
for(int x=0;x<gridCells[x].length-1; x++)
{
for(int y=0; y<gridCells[x].length-1; y++)
{
System.out.print(gridCells[x][y] + " ");
}
System.out.println();
}
}
}
最佳答案
public void populateGrid()
{
for(int x =0; x<gridCells[x].length-1; x++) // -1 to avoid outofboundsexception error
{
for(int y =0; y<gridCells[y].length-1; y++)
{
gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a');
}
}
}
这都是假的,无论你这样做 index < array.length
或index <= array.length-1
。
index < array.length-1
很可能不是您想要的。
此外,如果出现编译错误,可能是因为您没有初始化 numberOfRegions。通常,这不是错误,而是警告,但在这种情况下,您的编译器可能会发出错误。尝试一下
private int numberOfRegions = 0;
关于java - 使用 import java.util.Random; nextInt 和用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20216486/