输入的产品总数和使用Switch输入的所有产品的总数

时间:2017-10-04 03:09:23

标签: java

我试图让我的输出显示输入的每个项目的总成本和所有项目的总成本,程序运行但是当我尝试使用文件结束指示时没有任何反应,什么我错过了吗?

package switch1;
import java.util.Scanner;

public class Switch1 {

    public static void main(String[] args) {
        double total = 0;
        int productCounter = 0;
        int aProduct = 0;
        int bProduct = 0;
        int cProduct = 0;
        int dProduct = 0;
        int eProduct = 0;

        Scanner input = new Scanner(System.in);

        System.out.printf("%s%n%s%n    %s%n    %s%n",
                "Select your product(1=bread, 2=cheese, 3=meat, 4=msutard, 5=mayo)",
                "Type the end-of-file indicator to terminate input:",
                "On UNIX/Linux/macOS type <Ctrl> d then press Enter",
                "On Windows type <Ctrl> z then press Enter");

        while (input.hasNext()) {
            int product = input.nextInt();
            total += product;
            ++productCounter;

            switch (product) {
                case 1:
                    ++aProduct;
                    break;
                case 2:
                    ++bProduct;
                    break;
                case 3:
                    ++cProduct;
                    break;
                case 4:
                    ++dProduct;
                    break;
                case 5:
                    ++eProduct;
                    break;
            }
        }
        System.out.printf("%nProduct Selection:%n");

        if (productCounter != 0) {
            double aTotal = (aProduct * 1.89);
            double bTotal = (bProduct * 3.99);
            double cTotal = (cProduct * 6.99);
            double dTotal = (dProduct * 1.99);
            double eTotal = (eProduct * 2.99);
            total = (((double)aProduct * 1.89) + ((double)bProduct * 3.99) + ((double)cProduct * 6.99) + ((double)dProduct * 1.99) + ((double)eProduct * 2.99));

            System.out.printf("You ordered %d gallons of milk totaling: %f%n", aProduct, aTotal);
            System.out.printf("You ordered %d loaves of bread totaling: %f%n", bProduct, bTotal);
            System.out.printf("You ordered %d packages of cheese totaling: %f%n", cProduct, cTotal);
            System.out.printf("You ordered %d pounds of meat totaling: %f%n", dProduct, dTotal);
            System.out.printf("You ordered %d bottles of mustard totaling: %f%n", eProduct, eTotal);
            System.out.printf("Your total grocery bill is: %d%n", total);
        }
        else {
            System.out.println("No products were entered");
        }
    }

}

2 个答案:

答案 0 :(得分:0)

将scanner.hasNext替换为scanner.hasNextLine。如果您使用换行符并按CTRL-D(linux)或CTRL-Z(Windows),则hasNextLine应返回false。

答案 1 :(得分:0)

也许一个更好的问题是“我怎么知道我做错了什么?” 一步就是在try-catch块中扭曲代码,如:

        try {   
            //the code goes here 
        }catch(Exception ex) {
            ex.printStackTrace();
        }

并查看例外情况。 它将指示此行中的问题

System.out.printf("Your total grocery bill is: %d%n", total);