java - I don't know why the variables are not initializing, all variables declared inside if statements aren't recognized -


i can't figure out why variables aren't being able printed

 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 string        string inputstr = br.readline();        //verify input integer        int numbags = integer.parseint(inputstr);        //make sure number above 0        if (numbags <= 0)              system.out.print("please purchase @ least 1 bag.");        if (numbags <= 0)              system.exit(0);         //calculate purchase price        double purchaseprice = single_price * numbags;         //set numbagsleft numbags        int numbagsleft = numbags;         //determine number of large boxes needed        if (numbagsleft >= 20) {            int largeboxcount = numbagsleft / 20;        }         //reinitialize number of bags 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;;)        }   } 

okay. code supposed take in number of "coffee bags", , then, using system of if statements, filter down through in order find out how many boxes need purchase in order best save money. problem i'm having variables such largeboxcount , mediumboxcount not being initialized, , aren't able called when go print them.

i see scoping issues. variables declared inside of if block visible inside if block , not outside of it. declare variables before if blocks , in main method.

bar = 0; // declared before if block, visible inside , out if (foo) {    bar = 1; // variable visible outside of if block    int baz = 1; // variable not visible outside of if block }  system.out.println("bar = " + bar); // legal system.out.println("baz = " + baz); // illegal  

Comments