AldoT AldoT - 7 months ago 8
Java Question

How to use a value from the if statement?

I am trying to use a value that is created inside an "if statement" and print it outside of it but to create a pop up it does not recognize it and I do not know why. Can someone help me please??

@Override
public void onClick (View v){
int sum = uno + dos + tres + cuatro;
double pru = sum*8;
if(sum == 11){
double tot = pru - (pru*.01);
String tot1 = String.valueOf(tot);
}
if(sum == 12){
double tot = pru - (pru*.02);
String tot1 = String.valueOf(tot);
}
if(sum == 13){
double tot = pru - (pru*.03);
String tot1 = String.valueOf(tot);
}
if(sum == 14){
double tot = pru - (pru*.04);
String tot1 = String.valueOf(tot);
}
if(sum == 15){
double tot = pru - (pru*.05);
String tot1 = String.valueOf(tot);
}
if(sum == 16){
double tot = pru - (pru*.06);
String tot1 = String.valueOf(tot);
}
if(sum == 17){
double tot = pru - (pru*.07);
String tot1 = String.valueOf(tot);
}
if(sum == 18){
double tot = pru - (pru*.08);
String tot1 = String.valueOf(tot);
}
if(sum == 19){
double tot = pru - (pru*.09);
String tot1 = String.valueOf(tot);
}
if(sum >= 20){
double tot;
tot = pru - (pru*.1);
String tot1 = String.valueOf(tot);
}

print tot1;


Thanks in advance!

Answer

I suggest you read this: https://en.wikipedia.org/wiki/Scope_%28computer_science%29

The short answer is that you can't do what you're trying to do. A variable born in an if block vanishes when you exit the if block. That is known as a variable "going out of scope".

To solve your issue, declare the variable outside your if block. I won't reproduce your entire code, but it will look something like this:

int sum = uno + dos + tres + cuatro;
double pru = sum*8;
String tot1 = "";
if(sum == 11){
    double tot = pru - (pru*.01);
    tot1 = String.valueOf(tot);
}
print tot1;

Just do that for all of your if statements.

Comments