我不知道为什么变量没有初始化,如果语句无法识别,则在里面声明的所有变量



我不明白为什么变量不能被打印

 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("nnNumber of Bags ordered: " + numBags + " - " + purchasePrice 
       + "nBoxesUsed: "
       + "n            "+largeBoxCount+" Large - $+largeBoxCount*1.80
       + "n            "+mediumBoxCount+" Medium - $"+mediumBoxCount*1.00
       + "n            "+smallBoxCount+" Small - $"+smallBoxCount*.60
       + "nnYour total cost is: $"+largeBoxCount*1.80+mediumBoxCount*1.00+smallBoxCount*.60+purchasePrice;;)
       }

}

好吧。因此,代码应该接收一些"咖啡袋",然后使用if语句系统进行过滤,以找出您需要购买多少盒才能最有效地省钱。我遇到的问题是,诸如largeBoxCount和mediumBoxCount这样的变量没有被初始化,因此当我去打印它们时无法调用。

我看到一些范围问题。在if块内部声明的变量只在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 

在 if语句中声明变量,当作用域结束时,它们将被删除。

最新更新