检查数组中的负数并重新提示输入正确

时间:2015-12-04 00:00:57

标签: java arrays user-input

我们的想法是创建一个星期内赚钱的平均值,我的平均值必须使用main方法中调用的方法计算。这是一个简单的部分,但我坚持的部分是如果输入的数字小于零,它应该给我一个错误信息,并重新提示用户更好的价值。我不是在寻找一份讲义,只是为了告诉我,如果它简单易行,或者指针朝着正确的方向,那么我做错了什么。

import java.util.*;

public class weeklyAveragesClient2
{
    public static void main(String [] args)//output averages in format
    {
        averageCash();
    }

    public static double averageCash()//use array and loop to calculate weekly average
    {
        double [] cashMoney;
        cashMoney = new double[7];
        Scanner scan = new Scanner(System.in);
        int j = 0;
        String s = "ERROR";

        while (j < 7)
        {     
            double num = cashMoney[j]; 

            if (num == 0)
            {
                System.out.println("Error please enter a number > 0");
                num = j;
                cashMoney[j] = scan.nextDouble();
            }
            else if(num > 0)
            {
                System.out.print("Please enter an amount for day " + (j+1) +": ");
                cashMoney[j] = scan.nextDouble();
                j++;
            }
            else
            {
                System.out.println("Error: negative number please enter a number >       0");
            }
        }
        System.out.println("Calculating...");

        double sum = 0;
        for (int i = 0; i < cashMoney.length; i++)
        {
            sum = sum + cashMoney[i];
        }
        double average = sum / (double)cashMoney.length;
        System.out.println("Average: " + average);
        return average;
    }//end averageCash
}//end class

1 个答案:

答案 0 :(得分:0)

我已经添加了一些有助于提供思考的评论。

// This will *always* be zero at first because you haven't called scan.nextDouble() yet 
// and zero is the default value. So when you run the program, it will output "Error 
// please enter a number > 0" before doing anything else
if (num == 0) {
    System.out.println("Error please enter a number > 0");
    num = j;
    cashMoney[j] = scan.nextDouble();
} else if (num > 0) {
    System.out.print("Please enter an amount for day " + (j + 1) + ": ");
    cashMoney[j] = scan.nextDouble();
    j++;
} else {
    // If we get into this state, the user will never be invited to enter 
    // another number, since the last entered number was negative, so 
    // num == 0 is false, and
    // num > 0 is false, so
    // we'll end up back here. In fact, you'll enter an infinite loop and
    // this message will be printed over and over again.
    System.out.println("Error: negative number please enter a number >       0");
    // cashMoney[j] = scan.nextDouble(); // <-- try prompting the user again
}

还请考虑正确缩进代码。它将大大提高可读性。如果您使用的是像Eclipse这样的IDE,则可以选择Source&gt;格式。