[英]Why does my method sometimes print multiple lines?
所以我有這種方法
public int sumMathRandomAndSystemTime(){
n = 1 + ((int) (Math.random() * 10)+
(int) (System.currentTimeMillis() % 10));
if(n > 10){
sumMathRandomAndSystemTime();
}
System.out.println(n);
return n;
}
我只想在1到10之間打印一個隨機數(n)一次。 但是由於某種原因,當我調用該方法時,它確實會打印一個隨機數,但有時只會打印一次,而有時會打印一次,例如10次,5次等。為什么會這樣呢?
這是我的輸出示例
10
10
10
10
10
如果原始隨機數大於10,則您的代碼將打印多行:每個遞歸調用一行。
您可以按以下方式更改代碼以解決此問題:
public int sumMathRandomAndSystemTime(){
int n = getRandomNumber();
System.out.println(n);
return n;
}
public int getRandomNumber() {
int n = 1 + ((int) (Math.random() * 10)+
(int) (System.currentTimeMillis() % 10));
if(n > 10){
n = getRandomNumber();
}
return n;
}
通常,更簡單的代碼是:
public int sumMathRandomAndSystemTime(){
Random random = new Random();
int n = random.nextInt(10);
System.out.println(n);
return n;
}
如果您只想打印1到10之間的一個隨機數,請嘗試這樣的操作...
int n;
do
{
n = 1 + ((int) (Math.random() * 10) + (int) (System.currentTimeMillis() % 10));
} while(n > 10);
return n;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.