提问者:小点点

如何使用双打的用户输入关闭while循环


所以,免责声明,这是一门课,但我已经提交了作业,并向教授寻求帮助,所以我没有作弊或请别人做作业。 在这个过程中,我也花了几个小时浏览这个网站。

我试图获得多达52次的用户输入,把它们加在一起,然后平均和。

我制作这个方法是为了允许用户根据代码中进一步输入的销售变量输入他们的周利润。 我认为限制为52个会很好,因为它可以让一个人平均工作2周,一个月,6个月等等,就像他们试图预算或寻找一个估计的年收入一样。

    //new method
    public static void computeAverageSalesProfit() {       

        //new scanner object in method
        Scanner input = new Scanner(System.in);

        //new object
        Sales AvgProfit = new Sales();

        //prompt for input
        System.out.println("Please enter weekly profits, up to 52 weeks.  When finished, enter '-1.'");       

        //value to store input, and test against
        double value = 0;
        //new double array to sum together and average out
        double[] sum2 = new double[52];

        //while loop of doom
        while(value >= 0) {

        for (int i=0; i<sum2.length; i++) {
        value = input.nextDouble();
        sum2[i] = value + 0;

        }
        }

        double WeeklyProfits = 0;
        for (int i=0; i<sum2.length; i++) {
            WeeklyProfits = sum2[i] / sum2.length;
        }

        AvgProfit.setWeeklyProfits(WeeklyProfits);

        System.out.printf("Your average profits are %.2f", AvgProfit.getWeeklyProfits());

    }

这是我今晚结束的代码,我不知道如何结束while循环。 我最初没有value变量,但认为在sum2迭代之前对它进行检查将允许我关闭它。 当我运行程序时,它接受用户输入,但直到我达到52次迭代才结束。 我还尝试在布尔表达式中使用“0000”,但也没有用。

我也尝试了没有设置值变量,我已经尝试了所有我能想到的和能在互联网上找到的方法。 我尝试使用和不使用一个值变量,只使用一个普通的双倍(不是数组)。 我甚至尝试使用一个字符串,使用一个布尔表达式(good=true/false,while(!/good)等,但是我无法转换为double和平均值。

我完全被迷住了,我的头很疼。 如果你能提供任何帮助或见解,我将非常感激。 谢谢。

哦,我在代码的另一部分中有一个while循环,它确实工作,但我不认为这一个是以同样的方式工作的。 我想我不是想多了,就是错过了一些很明显的东西。

//Check Year length separate, keeping original code mostly intact
    public static boolean isValid(String input)
    {
        //Does it have 4 digits?
        if(input.length() != 4)
            return false;

    // Is it a number ?
        try
        {
            Integer i = Integer.parseInt(input);
        }
        catch(NumberFormatException e)
        {
            return false;
        }

        // Passed all checks and is valid
        return true;
    }    

共1个答案

匿名用户

您可以做的一件事是使用for循环而不是while循环,如下所示:

//value to store input, and test against
double value = 0;
//new double array to sum together and average out
double[] sum2 = new double[52];

// repeats 52 times max
for (int i=0; i<sum2.length; i++) {
    value = input.nextDouble();

    // Checking if the user entered a negative number
    if (value < 0) {
        // The break keyword exits a loop
        break;
    }

    sum2[i] = value + 0;
}