java if then语句

标签 java

我希望程序检查需要多少个大盒子,然后使用余数来确定需要多少个中盒子,并对小盒子执行相同的操作。 但是当我运行这个时

第一步确定大盒子

变量 pensnotinbox 尽管我知道应该有余数,但结果为 0

   pen.setName("Awesome Pen");
     pen.setPrice(5.0);
     pen.setUPC(102);
     pen.setMediumCapacity(50);
     pen.setLargeCapacity(100);

     //printing information about the product to the user, and asking how many of this item they want to purchase
     System.out.print("Product 2 \n"   + "Name:" + pen.getName() + "    Price: " + pen.getPrice() + "    UPC: " + pen.getUPC() + "\n");
     System.out.print("How Many Of These Would You Like To Purchase?\n" );
     //using the scanner to get the integer/quantity they want
     penquant = scan.nextInt();
      //storing the total price in a variable 

        int penlargeboxes;
        double penboxes;
        int penmediumboxes;
        double penremainder;
        double pensnotinbox;
         int pensmallboxes;

      if (pen.getLargeCapacity() <= penquant) {
          penlargeboxes = penquant/pen.getLargeCapacity(); 
          penremainder = penquant % pen.getLargeCapacity(); 


          System.out.print(penlargeboxes + "\n");
          System.out.print(penremainder + "\n");


           if (penremainder > 0 ) {

              penboxes = penremainder/pen.getMediumCapacity() ;
              penmediumboxes = ((int)penboxes);
              penremainder =  penquant % pen.getLargeCapacity(); 

              pensnotinbox = penremainder;

              System.out.print(penmediumboxes + "\n");
              System.out.print(pensnotinbox + "\n");

            }else {
                if (penremainder > .99 ) {

               penboxes = penremainder/1 ;
               pensmallboxes = ((int)penboxes);

                  System.out.print(pensmallboxes + "\n");


            }

            }

     } else {
          System.err.println("OOPS!");
     } 


     pentotal= (pen.totalPurchase(penquant));
     //printing their total cost for this item
     System.out.print("The total cost for this item will be " + pentotal + "\n" + "\n");

最佳答案

penquantpen.getLargeCapacity() 的类型是什么?如果它们都是整数,则您正在执行没有小数部分的整数除法(余数被丢弃)。然后整数结果将提升为 double 。

所以如果是这种情况你可以尝试

penboxes = ((double)penquant)/pen.getLargeCapacity();

关于java if then语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5407378/

相关文章:

java - 如何查找远程系统 MAC 地址

java - Eclipse Java 应用程序刚刚终止

Java 7 list 安全更改

java - 线程安全的多重集

java - jsr 303 如何强制它使用我的资源包?

java - 点对点聊天安全选项?

java - 优化两个列表比较

java - 扩展 Android 的默认 Gmail/电子邮件应用程序

java - Powermockito : using thenReturn efficiently

java - 在一定时间后退出程序 - Java