使用哨兵驱动的外部 While 循环询问用户是否希望生成一组新的随机数
Use an outer While Loop that is sentinel driven to ask the user if they wish to generate a new set of random numbers
这是我目前所知道的,但由于某种原因,程序声明操作已完成,但不允许用户输入 1 或 2 以继续或不继续。提前致谢..
我的代码:
import java.util.Random;
public final class Kidwell_Lab09 {
public static Random generator = new Random();
public static void main(String[] args) {
int x;
int[] randomNumbers = new int[20];
do
{
Random generator = new Random();
for (int i = 0; i < randomNumbers.length; i++){
int n = generator.nextInt(10)+1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = generator.nextInt();
}
while ( x == 1 );
}
}
您应该从 System.in 而不是 generator.nextInt() 中读取值。
这是更正后的代码。
import java.util.Random;
public final class Kidwell_Lab09 {
public static Random generator = new Random();
public static void main(String[] args) {
int x;
int[] randomNumbers = new int[20];
Scanner inputReader = new Scanner(System.in);
do {
Random generator = new Random();
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
}
这是我目前所知道的,但由于某种原因,程序声明操作已完成,但不允许用户输入 1 或 2 以继续或不继续。提前致谢..
我的代码:
import java.util.Random;
public final class Kidwell_Lab09 {
public static Random generator = new Random();
public static void main(String[] args) {
int x;
int[] randomNumbers = new int[20];
do
{
Random generator = new Random();
for (int i = 0; i < randomNumbers.length; i++){
int n = generator.nextInt(10)+1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = generator.nextInt();
}
while ( x == 1 );
}
}
您应该从 System.in 而不是 generator.nextInt() 中读取值。
这是更正后的代码。
import java.util.Random;
public final class Kidwell_Lab09 {
public static Random generator = new Random();
public static void main(String[] args) {
int x;
int[] randomNumbers = new int[20];
Scanner inputReader = new Scanner(System.in);
do {
Random generator = new Random();
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
}