[英]Generating a random number in a loop
我想知道您將如何在循環中生成一個隨機數。 我知道我應該使用java.util.random
,但是我想知道應該怎么做,因為事實是,我需要生成程序需要的盡可能多的項隨機數,因為它的排序算法。
例如,首先,您需要選擇使用的是哪種方法(例如1),然后輸入數字時,接下來需要輸入計數項(例如5),然后,您需要選擇輸入項目(因此,如果您有5個項目,則需要輸入5個不同的項目,然后進行排序。
我需要生成這些數字,因為如果需要例如10000計數,我不想手動輸入10k的數字,因此自動進行輸入會很不錯。
希望你能幫助我! 抱歉,如果我錯了什么,這是我在這里的第一篇文章。 :)
ps我在這里添加了部分代碼,因此您可以看到我的循環。
public static void main(String[] args) { //3.part - array output
int numurs;
int metode;
System.out.println("Name Surname RDBF0 student no");
System.out.print("method: ");
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()){
numurs = sc.nextInt();
}
else
{
System.out.println("input-output error");
sc.close();
return;
}
if (numurs != 1 && numurs != 2) {
System.out.println("input-output error");
sc.close();
return;
}
System.out.print("count: ");
if (sc.hasNextInt())
metode = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
int a[] = new int[metode];
System.out.println("items: ");
for (int i = 0; i < a.length; i++) {
if (sc.hasNextInt())
a[i] = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
}
sc.close();
switch (numurs) {
case 1: firstMethod(a);
break;
case 2: secondMethod(a);
break;
default:
System.out.println("input-output error");
return;
}
System.out.println("sorted: ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
}
}
您可以使用Random類生成一個隨機數,如您所說:
Random rand = new Random();
//if you want the random number to be between 0 and maxValue
int randomNumber = rand.nextInt(maxValue);
//if you want it to be between minValue and maxValue, it should look like this
int randomNumber = rand.nextInt(maxValue) + minValue;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.