我无法得到总和来计算。我甚至不确定我的逻辑是否正确

时间:2016-09-27 01:17:16

标签: java

我相信我可能需要使用而不是同时,我不确定如何解决这个问题。当我尝试研究这一切时,我能找到的是关于"数组的总和"虽然我已经宣布了这些值,但我的总和仍然等于10。有人可以帮忙吗?谢谢

public class OnlinePurchases {
 public static void main(String[] args) {
  // TODO code application logic here

  String sName = " ";
  int nChoices = 0;
  int nChoice1 = 249;
  int nChoice2 = 39;
  int nChoice3 = 1149;
  int nChoice4 = 349;
  int nChoice5 = 49;
  int nChoice6 = 119;
  int nChoice7 = 899;
  int nChoice8 = 299;
  int nChoice9 = 399;
  int nSum = 0;
  final int SENTINEL = 10;
  int nCount = 0;

  Scanner input = new Scanner(System.in);

  System.out.print("Please enter your name : ");
  sName = input.nextLine();

  System.out.println("BEST PURCHASE PRODUCTS \n");
  System.out.println("1.   Smartphone $249");
  System.out.println("2.   Smartphone case $39");
  System.out.println("3.   PC Laptop $1149 ");
  System.out.println("4.   Tablet $349");
  System.out.println("5.   Tablet case $49");
  System.out.println("6.   eReader  $119");
  System.out.println("7.   PC Desktop $899");
  System.out.println("8.   LED Monitor $299");
  System.out.println("9.   Laser Printer $399");
  System.out.println("10. Complete my order");

  System.out.println("");

  System.out.print("Please select an item from the menu above : ");
  nChoices = input.nextInt();

  while (nChoices != SENTINEL) {
   System.out.print("Please select another item from the menu above : ");

   nCount++;

   nChoices = input.nextInt();

   if (nChoices == 1) {
    nChoices = nChoice1;
   } else if (nChoices == 2) {
    nChoices = nChoice2;
   } else if (nChoices == 3) {
    nChoices = nChoice3;
   } else if (nChoices == 4) {
    nChoices = nChoice4;
   } else if (nChoices == 5) {
    nChoices = nChoice5;
   }
  }

  nSum = nSum + nChoices;
  System.out.println("Price of Items Ordered : " + nSum);
  System.out.println("Total Items Ordered : " + nCount);
 }
}

2 个答案:

答案 0 :(得分:0)

您正在使用变量nChoices来检查输入的数字。当您想要停止程序时,10是输入的最后一个数字,因此10是添加到nSum的数字。要解决此问题,首先应在输入while循环之前检查第一个输入,然后检查while循环结束时的输入,这样如果选择10,则不会再次循环。此外,在每个if / else if语句下,您应该使用:

nSum += nChoiceWhatever //"Whatever" being the number correlated to your prices

答案 1 :(得分:0)

你的while循环很好。

您的问题正在发生,因为选择了一个选项后,您实际上并没有添加到您的nSum变量中。因此,当打印出总和时,实际上是在打印

nSum = nSum + nChoices = nSum = 0 + 10

这就是为什么你不断得到10的价值。

要解决这个问题,请用

替换你的nChoices if语句
if (nChoices == 1) {
    nSum += nChoice1;
} else if (nChoices == 2) {
    nSum += nChoice2;
} else if (nChoices == 3) {
    nSum += nChoice3;
} else if (nChoices == 4) {
    nSum += nChoice4;
} else if (nChoices == 5) {
    nSum += nChoice5;
}