当我为产品输入-1但不为两个输入-1时,如何使其中断

时间:2018-04-25 13:27:39

标签: java

我的结果要我:当我输入-1时(输入产品编号)它将直接中断并计算总数,但是现在我必须输入-1(输入产品编号)和(输入数量)只会打破

import java.util.Scanner;
public class Structuredcontrols {
   public static void main(String[]args) {      
      Scanner input = new Scanner(System.in);
      double sum=0;         
      double sum2=0;        
      double sum3=0;        
      int number = 0;       
      int quantity;         

      while (number != -1) {
          System.out.print("Enter product number: ");       
          number = input.nextInt(); 

          System.out.print("Enter quantity number: ");      
          quantity = input.nextInt();
          switch (number) {    
             case 1:
                 sum += 2.98 * quantity;
                 break;
             case 2:
                 sum2 += 4.50 * quantity;
                 break;
             case 3:
                 sum3 += 9.98 * quantity;
                 break;
          }

      }
      System.out.println("Total value of product 1 is: "+sum);
      System.out.println("Total value of product 2 is: "+sum2);
      System.out.println("Total value of product 3 is: "+sum3);

   }

}

1 个答案:

答案 0 :(得分:1)

只需添加import java.util.Scanner; public class structuredcontrols { public static void main(String[] args) { Scanner input = new Scanner(System.in); double sum = 0; double sum2 = 0; double sum3 = 0; int number = 0; int quantity; while (number != -1) { System.out.print("Enter product number: "); number = input.nextInt(); if (number == -1) break; System.out.print("Enter quantity number: "); quantity = input.nextInt(); switch (number) { case 1: sum += 2.98 * quantity; break; case 2: sum2 += 4.50 * quantity; break; case 3: sum3 += 9.98 * quantity; break; } } System.out.println("Total value of product 1 is: " + sum); System.out.println("Total value of product 2 is: " + sum2); System.out.println("Total value of product 3 is: " + sum3); } } 声明

即可
LEAD

这里的完整代码

LAG