Saturday, February 21, 2015

Getting an error " variable may not have been initialized'


Hey guys, I know what the error means but I don't think initializing the variable will make my code work as intended so I'm having a little dilemna here... here's the code and I'll highlight the part that is said to be not initialized:



Java Code:



import java.util.Scanner;

public class ItemCost {
public static void main (String []args){
int i=1,item=1,e=1, f=1, g=1;
int items, d ;
double gst, qst, subt, Tot = 1, PriceItems ;
Scanner x = new Scanner(System.in);
Scanner y = new Scanner(System.in);
Scanner z = new Scanner(System.in);
Scanner w = new Scanner(System.in);


System.out.println("Please input the amount of items bought");
items = x.nextInt();

while ( items < 1 || items > 10)

{
System.out.print("Sorry the input was not correct, please try again\n");
items = x.nextInt();
i++;
}

do
{
System.out.print("Please input the price of the item "+item + " " );
PriceItems = y.nextDouble();
[B][SIZE=4] subt += PriceItems;[/SIZE][/B]
if
( PriceItems < 1 || PriceItems > 1000 )
e++;
else
item++;
}while (item <= items);



System.out.println("Please input the rate of GST in %");
gst = z.nextDouble();

while (gst < 0 || gst > 22)
{
System.out.print("Sorry, this was incorrect, please try again");
gst = z.nextDouble();
f++;
}



System.out.println("Please input the rate of QST in %");
qst = w.nextDouble();

while (qst < 0 || qst > 18)
{
System.out.print("Sorry, this was incorrect, please try again");
qst = z.nextDouble();
g++;
}
}
}

So I'm supposed to get the following output :

Java Code:



Please input the amount of items bought
2
Please input the price of the item 1 1
Please input the price of the item 2 2
Please input the rate of GST in % 20

Please input the rate of QST in % 18

HOWEVER my program doesn't seem to add input of item 1, and 2 if I initialize subt= 0 initially. It'll only take the last value inputted in the loop. By the way, the increments are counters to count the amount of errors the user might input by accident ( or whatever). Some people have been pointing it out as useless but that's the only way I found it to work.

THanks for the help in advance guys!



No comments:

Post a Comment