试图弄清楚为什么我的数学不加

时间:2019-10-21 15:00:01

标签: java

我目前正在为一个大学项目工作,该项目要求您创建基本的购物菜单。我目前通过将项目数量乘以成本来求和,但总数保持为零。我创建了单独的整数来存储物料的成本(例如:int hat = 32)和数量的单独整数(例如:quanHat = 0)。由于某种原因,即使我添加了++,项目的数量仍保持为零。有人帮我吗?

我尝试过将整数转换为字符串然后返回,但是似乎没有任何作用。

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Pirate Trading Post v3");
    System.out.println("----------------------");
    int eight = 8;
    int hat = 32;
    int patch = 2;
    int sword = 20;
    int map = 100;
    int shirt = 150;
    int test = -1;
    int quanEight = 0;
    int quanHat = 0;
    int quanPatch = 0;
    int quanSword = 0;
    int quanMap = 0;
    int quanShirt = 0;
    int total = ( quanEight * eight) + ( quanHat * hat) + ( quanPatch * patch) + ( quanSword * sword) + ( quanShirt * shirt) + ( quanMap * map);
    while (test != 0){
        System.out.println("Enter Item Code, ? or Q: ");
        String code = input.next();
        char ch = code.charAt(0);
        ch = Character.toUpperCase(ch);

        if (ch == '?'){
            System.out.println("Valid Item codes are: 8 I H M S T.");
            System.out.println("Q to quit.");
        }
        else if (ch == 'Q'){
            test++;
            System.out.println("Pirate Trading Post");
            System.out.println(quanEight + " Genuine Piece Of Eight " + quanHat + " Pirate Hat " + quanPatch + " Eye Patch " + quanSword + " Sword " + quanMap + " Treasure Map " + quanShirt + " T-Shirt ");
            System.out.println("Total: " + total + " bits");

        }
        else if (ch == '8'){
            quanEight ++;

        }
        else if (ch == 'I'){
            quanHat++;
        }
        else if (ch == 'H'){
            quanPatch++;
        }    
        else if (ch == 'M'){
            quanSword++;
        }
        else if (ch == 'S'){
            quanMap++;
        }
        else if (ch == 'T'){
            quanShirt++;
        }

    }

预期输出应为物料成本乘以数量,但数量不会存储值。我认为该值不是存储的,因为它是一个字符串,但是我不确定。

1 个答案:

答案 0 :(得分:0)

当代码计算出total时,quanHat为0。因此total被赋值为0。

在quanHat递增的while循环期间,其值递增1。

但是由于total尚未更新或重新计算,因此仍显示为0。

您需要在else if (ch == 'Q')的if块中重新计算总数