如何设置负的Sentinel值?

时间:2015-03-11 02:25:56

标签: java sentinel

我在大学Java课程中,我们刚刚学习了方法。但是,我似乎在设置Sentinel值时遇到了一些问题。我有一个正确的设置,显然已经设置为0.但是现在我必须为任何和所有负值设置一个,但它似乎没有工作。这是我的代码:

    import java.util.Scanner;

    public static void main(String[] args) {

    //States and initializes multiple variables.
    int id;

    //Creates the scanner class.
    Scanner keyboard = new Scanner(System.in);

    //Introduces the USER as to what they are inputing.
    System.out.println("Hello. Welcome to our webpage. Please enter your ID"
            + " before continuing."
            + " Valid IDs are between 10000 and 40000.");
    System.out.println();

    do {
        System.out.print("ID: ");
        id = keyboard.nextInt();
        if ((id < 10000 || id > 40000)) {
            System.out.println("Invalid input detected. Please try again.");
        }
    } while ((id < 10000 || id > 40000));
    System.out.println();

    calcSubtotal();
}

public static double calcSubtotal() {

    double testPrice = -1, itemPrice = 0;
    int count = 0;

    Scanner input = new Scanner(System.in);

    while (testPrice != 0) {

        //Takes user input, while also addressing it a count.
        System.out.print("Enter item price or zero or a negative value"
                + " to quit => ");
        testPrice = input.nextDouble();
        if (testPrice != 0) {
            itemPrice += testPrice;
            count++;
        } else if (testPrice < -1) {
            itemPrice += testPrice;
            count++;
        }
    }

    System.out.println("Count test: " + count);

    return itemPrice;
}

}

1 个答案:

答案 0 :(得分:0)

您在"enter a negative value to quit"方法中说calcSubtotal,但在输入负值时,您实际上从未退出循环。尝试对此实施类似的方法:

if (value < 0) { 
   //Do some stuff once you detect the negative sentinel value
   //Then break out of the loop which will exit THE ENTIRE LOOP immediately
   //after the current value being evaluated is negative
   break;
{

还想指出你永远不会处理testPrice等于-1,你应该使用&lt; = -1或&lt; 0所以处理所有负面情况。