我目前正在为一个大学项目工作,该项目要求您创建基本的购物菜单。我目前正在通过将项目数量乘以成本来求和,但总数保持为零。我创建了单独的整数来存储物料的成本(例如: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++;
}
}
预期输出应为项目成本乘以数量,但数量不会存储值。我认为该值不是存储的,因为它是一个字符串,但是我不确定。
最佳答案
当代码计算出total时,quanHat为0。因此将total赋值为0。
在while循环中,当quanHat递增时,其值递增1。
但是由于总计未更新或重新计算,因此仍显示为0。
您需要在else if (ch == 'Q')
的if块中重新计算总数