这是我现在拥有的代码。
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
int set[] = new int[5];
set[0] = (int)(Math.random()*6)+1;
set[1] = (int)(Math.random()*6)+1;
set[2] = (int)(Math.random()*6)+1;
set[3] = (int)(Math.random()*6)+1;
set[4] = (int)(Math.random()*6)+1;
System.out.println("Your current dice: " + set[0] + " " + set[1] + " " + set[2] + " " + set[3] + " " +set[4] );
System.out.println("Select a die to re-roll (-1 to keep remaining dice):");
int ask = keyboard.nextInt();
在此之后,如果用户输入 1,则 set[1]
应更改为数字零,因此它变为 x0xxx
并且如果用户还想要要更改的第三个数字应该是 x0x0x
。
顺便说一下,x
只是生成的随机数。
我该如何继续这样做?总共不得超过 5 次。
最佳答案
以下是您应该遵循的基本步骤来完成您想要/需要的任务。
- 读取用户输入(使用
扫描仪
或其他工具)。 - 验证用户输入是否是数组的有效索引(即输入是一个值在 0 到 5 之间的数字)。您可以将其存储在变量
int x
中。 - 将用户输入的索引内的数组元素的值更改为 0(或您想要/需要的值)。这会导致类似于
set[x] = ...
的内容(将...
更改为正确的值)。
关于java - 如何更改数组的每个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292758/