0

私は大学の 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;
}

}

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 に答える