Java虽然看起来正确编码返回值?

时间:2011-08-02 14:30:31

标签: java

我的问题是关于增量我问你如何从do while循环返回数据,假设要在每个值中设置。

我的do while循环中的totalSales在循环出来时应该有数据集,它不会将数据保存到totalSales或totalItems值中。

// The system print out values are empty.
      System.out.printf(salesID + " you entered a total of: " + totalItems + "With a total sales of $%15.2f" + totalSales); 

我试图从一个怪异的do或if语句循环返回数据,它不会返回我设置的项目为什么?

// yesno to n for first loop through.

do {
      System.out.println("Welcome Sales ID: " + salesID + " please enter the samsung TV sold: \n");
      samsungProduct = scanValue.next();
      System.out.println("Please enter your total TV sales amounts individually for today \n");
      singleSale = scanValue.nextDouble();
      totalSales = totalSales + singleSale;
      totalItems = totalItems++;
      System.out.println("Do you want to enter another sales total(Y/N): \n ");
      yesNo = scanValue.next();

}        while (!yesNo.equalsIgnoreCase("N"));

// get the items set inside of the do while loop.

// The system print out values are empty.
      System.out.printf(salesID + " you entered a total of: " + totalItems + "With a total sales         of  $%15.2f" + totalSales); 

4 个答案:

答案 0 :(得分:6)

这是错误的:

totalItems = totalItems++;

你应该做

totalItems++;

你所做的就等于:

int temp = totalItems;
totalItems = totalItems + 1;// (totalItems++)
totalItems = temp;

答案 1 :(得分:4)

这是您的问题:totalItems = totalItems++;

在这行代码之后,totalItems的值不会改变。

使用totalItems++;代替

问题是i ++递增i,但返回旧值。所以,当你执行i = i++时,你将旧值分配给i - 所以我没有改变。

答案 2 :(得分:2)

totalItems = totalItems++;是无操作的。

请参阅此处Post Increment Operator And Assignment


System.out.printf(salesID + " you entered a total of: " + totalItems 
    + "With a total sales of $%15.2f" + totalSales);

应该是

System.out.printf(salesID + " you entered a total of: " + totalItems 
       + "With a total sales of $%15.2f", totalSales);
                                       ^^^^

答案 3 :(得分:1)

我没有看到你的循环出现任何明显错误,但是运行它(创建了适当的变量)导致了这个异常:

Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '15.2f'
    at java.util.Formatter.format(Formatter.java:2432)
    at java.io.PrintStream.format(PrintStream.java:920)
    at java.io.PrintStream.printf(PrintStream.java:821)
    at ScratchMain.main(ScratchMain.java:26)

这告诉我你没有正确使用printf。如果您使用$f(或更复杂的$%15.2f),那么您要放在那里的值需要作为参数传递给printf而不是刚刚连接到String

System.out.printf(salesID + " you entered a total of: " + totalItems + "With a total sales         of  $%15.2f", totalSales);

此外,你有代码totalItems = totalItems++;,这实际上是一个无操作(即它什么都不做)。将其替换为 <{em> totalItems++;totalItems = totalItems + 1;(如果您想明确说明)。