只允许来自“是/否”响应的真值答案

时间:2018-09-17 00:45:44

标签: java

我有这段代码可以创建发票金额。我试图做到这一点,所以我可以回答是/否(是或否),以便继续进行。但是,如果我给的答案不是“ Y”,它就会退出。我希望它只接受“ Y”和“ N”作为答案。

如果回答为“ N”,仍会打印字符串“ message”。

int main(int argc, char *argv[]) {
    bool chars_seen[256] = {0};

    for( int i = 1; i < argc; i++ ) {
      display_chars_no_dups( argv[i], chars_seen );
    }
    write(1, "\n", 1);
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以这样做:

 while (true){
  if(choice.equalsIgnoreCase("y"){
     System.out.print("Enter subtotal:   ");
            double subtotal = sc.nextDouble();

            // calculate the discount amount and total
            double discountPercent = 0;
            if (subtotal <= 100) {
                discountPercent = .1;
            } else if (subtotal <= 200) {
                discountPercent = .2;
            } else if (subtotal >= 500) {
                discountPercent = 0.25;
            }
            double discountAmount = subtotal * discountPercent;
            double total = subtotal - discountAmount;

            // display the discount amount and total
            String message = "Discount percent: " + discountPercent + "\n"
                           + "Discount amount:  " + discountAmount + "\n"
                           + "Invoice total:    " + total + "\n";            
            System.out.println(message);

            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
    }
    else if(choice.equalsIgnoreCase("n")){
        //....
        break;
   }
    else{
     System.out.print("Please enter (y/n): ");
            choice = sc.next();
            System.out.println();
}
}

OR:

 while (!choice.equalsIgnoreCase("n"){
  if(choice.equalsIgnoreCase("y"){
     System.out.print("Enter subtotal:   ");
            double subtotal = sc.nextDouble();

            // calculate the discount amount and total
            double discountPercent = 0;
            if (subtotal <= 100) {
                discountPercent = .1;
            } else if (subtotal <= 200) {
                discountPercent = .2;
            } else if (subtotal >= 500) {
                discountPercent = 0.25;
            }
            double discountAmount = subtotal * discountPercent;
            double total = subtotal - discountAmount;

            // display the discount amount and total
            String message = "Discount percent: " + discountPercent + "\n"
                           + "Discount amount:  " + discountAmount + "\n"
                           + "Invoice total:    " + total + "\n";            
            System.out.println(message);

            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
    }
    else{
     System.out.print("Please enter (y/n): ");
            choice = sc.next();
            System.out.println();
}
}