0

我在上大学 Java 课程,我们刚刚学习了方法。但是,我似乎在设置哨兵值时遇到了一些问题。显然,我已经正确设置了一个,并且设置为 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;
}

}

4

1 回答 1

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;
{

还想指出,您永远不会处理等于 -1 的 testPrice,您应该使用 <= -1 或 < 0 以便处理所有负面情况。

于 2015-03-11T02:34:22.197 回答