我目前正在开展一个大学项目,该项目要求您创建一个基本的购物菜单。我目前正在通过将元素数量乘以成本来计算我的数学总计,但总数仍为零。我创建了单独的整数来存储项目的成本(例如: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++;
}
}
预期输出应该是元素成本乘以数量,但数量不会存储值(value)。我认为该值未存储,因为它是一个字符串,但我不确定。
最佳答案
当代码计算total时,quanHat为0。因此total被赋值为0。
在 while 循环中,当 quanHat 递增时,其值会递增 1。
但由于总计未更新或重新计算,因此仍显示 0。
您需要在 else if (ch == 'Q') 的 if block 中重新计算总计
关于java - 试图找出为什么我的数学不会相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58489018/