如何在Java中在循环中重复执行随机数方法,直到达到true?

时间:2018-07-06 10:58:10

标签: java

pricee()方法返回双精度“ sum”,它是一个随机数。我希望这个随机数不断变化,直到小于10。

但是,循环仅运行一次,如果为true,则打印出“ sum”,如果为false,则给出错误。在随机数总和小于10之前如何调用此方法?

import java.util.Random;


public class Menu_algorithm {
    private static int[] anArray;
    private static double sum = 0;
    private static double monPrice;
    private static double tuePrice;
    private static double wedPrice;
    private static double thuPrice;
    private static double friPrice;
    private static double satPrice;
    private static double sunPrice;
    private static double[] prices = {1.25,3.10,1.78,2.1,1.76,2.12,1.43,1.22,0.11,0.32,0.42,0.66,0.74,2.22};

    public static int[] randList() {
        anArray = new int[7];
        for(int i=0;i<anArray.length;i++){
            anArray[i] = randomFill();
        }
        return anArray;
    }

    public static double pricee(){
        randList();
        monPrice = prices[anArray[0]];
        tuePrice = prices[anArray[1]];
        wedPrice = prices[anArray[2]];
        thuPrice = prices[anArray[3]];
        friPrice = prices[anArray[4]];
        satPrice = prices[anArray[5]];
        sunPrice = prices[anArray[6]];
        sum = monPrice + tuePrice + wedPrice + thuPrice + friPrice + satPrice + sunPrice;
        return sum;
    }

    public static void pCheck(){
        while (true){
            pricee();
            if (sum < 10){
                System.out.print(sum);
                break;
            }
        }
    }

    public static int randomFill(){
        Random rand = new Random();
        int randomNum = rand.nextInt(15);
        return randomNum;
    }

    public static void main(String args[]) {
        pCheck();
    }
}

1 个答案:

答案 0 :(得分:0)

函数pricee()会引起问题。这是因为您以这种方式获取元素:

prices[anArray[6]];

这意味着,如果您的randomFill()函数返回14并将其插入到anArray中,您将尝试从包含14个元素的价格列表中获取14个元素,因此最后一个元素的索引为13,程序将抛出IndexOutOfBoundException

在函数randomFill()替换

int randomNum = rand.nextInt(15);

收件人:

int randomNum = rand.nextInt(prices.length);