我不知道为什么变量没有初始化,所有在if语句中声明的变量都无法识别

时间:2015-07-09 21:26:53

标签: java

我无法弄清楚为什么变量无法打印

 import java.text.*;
   import java.io.*;

   public class CoffeeBags
   {

   //CONSTANTS
   public static final double SINGLE_PRICE = 5.5;

      public static void main( String[]args)
      throws IOException 
      {

      BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

       //Display Message "Enter Number of Bags Ordered: "
       System.out.print("Enter Number of Bags Ordered: ");
       //Save input as string
       String inputStr = br.readLine();
       //Verify that input is integer
       int numBags = Integer.parseInt(inputStr);
       //Make sure number is above 0
       if (numBags <= 0) 
            System.out.print("Please purchase at least one bag.");
       if (numBags <= 0) 
            System.exit(0);

       //Calculate purchase price
       double purchasePrice = SINGLE_PRICE * numBags;

       //Set numBagsLeft to numBags
       int numBagsLeft = numBags;

       //Determine Number of Large Boxes needed
       if (numBagsLeft >= 20) {
           int largeBoxCount = numBagsLeft / 20;
       }

       //Reinitialize Number of Bags to the remainder
       int numBagsLeft2 = numBagsLeft % 20;

       if (numBagsLeft2 >= 10) { 
           int mediumBoxCount = numBagsLeft2 / 10;
       };

       int numBagsLeft3 = numBagsLeft2 % 10;

       if (numBagsLeft3 > 0 && numBagsLeft3 <= 5){ 
           int smallBoxCount = 1;
       } else {
           int smallBoxCount = 2;
       }

       //Display 
       System.out.print("\n\nNumber of Bags ordered: " + numBags + " - " + purchasePrice 
       + "\nBoxesUsed: "
       + "\n            "+largeBoxCount+" Large - $+largeBoxCount*1.80
       + "\n            "+mediumBoxCount+" Medium - $"+mediumBoxCount*1.00
       + "\n            "+smallBoxCount+" Small - $"+smallBoxCount*.60
       + "\n\nYour total cost is: $"+largeBoxCount*1.80+mediumBoxCount*1.00+smallBoxCount*.60+purchasePrice;;)
       }


}

好。因此,代码应该包含许多“咖啡袋”,然后,使用if语句系统,向下过滤,以找出您需要购买多少个盒子,以便最好地省钱。我遇到的问题是诸如largeBoxCount和mediumBoxCount之类的变量没有被初始化,因此当我去打印它们时无法被调用。

2 个答案:

答案 0 :(得分:2)

我看到一些范围问题。在if块内部声明的变量仅在if块内部可见,而不在其外部。在if块之前和main方法中声明这些变量。

bar = 0; // declared before the if block, visible inside and out
if (foo) {
   bar = 1; // this variable is visible outside of the if block
   int baz = 1; // this variable is not visible outside of the if block
}

System.out.println("bar = " + bar); // legal
System.out.println("baz = " + baz); // illegal 

答案 1 :(得分:1)

你在if语句中声明了里面的变量,当范围结束时它们被删除了。