我有一個叫SnowFallReport
的類,當從中創建一個對象時,它會隨機將一個1-20的數字分配給一個名爲snowFall
的字段。目的是生成隨機雪量的虛擬雪情報告。然後我試圖創建一個方法,可以根據snowFall
字段中的數字顯示一定數量的星號。給了我一個暗示,我應該使用for
循環來做到這一點,但我無法弄清楚如何正確地說出它。碼如下:創建一個「for」循環,返回不同數量的字符
import java.util.Random;
public class SnowFallReport
{
// Random amount of snow
private double snowAmount;
// Default constructor creates random amount and assigns to snowAmount
public SnowFallReport()
{
Random snowFall = new Random();
snowAmount = (snowFall.nextDouble() * 20);
}
public double getSnow()
{
return snowAmount;
}
public String getStars()
{
for (int starCount = 0; starCount >= snowAmount; starCount++)
return "*";
/* This is what I thought it should be^ but it turns out I need a return
statement outside of the for loop. I've tried a couple of different ways with no luck */
}
public static void main(String[] args)
{
SnowFallReport day1 = new SnowFallReport();
String lol = day1.getStars();
System.out.print(lol);
}
}
'return'語句將切斷循環。程序流程將退出該功能。 – Oneb 2013-02-21 01:48:23