0

I am trying to get it so if i put a piece of code such as

if ((variable1 - variable2) < 0)
        int variable5 = (variable3 + variable4);

but this does not seem to work for me. So i was wondering if anyone had a solution?

10
  • 3
    Can you explain - doesn't work? Aug 6, 2014 at 9:10
  • You have to add some more explanation. What is variable,variable1...and what are there types and values? Aug 6, 2014 at 9:11
  • does your variable5 already exist? if so you can't declare it inside your if . you can do variable5 = (variable3 + variable4);
    – gkrls
    Aug 6, 2014 at 9:11
  • what is the value of variable 1 and variable
    – R D
    Aug 6, 2014 at 9:11
  • 2
    You have no brackets in your if statement, so variable 5 goes out of scope immediately.
    – kiwiron
    Aug 6, 2014 at 9:11

4 Answers 4

6

You're trying to declare a variable as the only statement in an if statement body. That's not allowed, as it would be pointless - the variable would be out of scope immediately afterwards. Either you should declare the variable first:

int variable5 = 0; // Or whatever value you want otherwise
if (variable1 - variabl < 0)
    variable5 = variable3 + variable4;

Or if you only need the variable within the body of the if statement, you'll need more statements:

if (variable1 - variabl < 0) {
    int variable5 = variable3 + variable4;
    // Use variable5
}

I would strongly encourage you to always use braces with if statements (and loops etc).

2
  • +1 for giving both possible uses, as opposed to just assuming the use. Aug 6, 2014 at 9:13
  • Yeah i still have a few minutes to accept it. But thanks im currently doing work experience and teaching my self java for it.
    – NatzoHD
    Aug 6, 2014 at 9:20
0

You can't declare a local variable if you only use 1 statement as the body of if.

Try this:

int variable5 = 0; // Default value
if (variable1 - variable < 0)
    variable5 = variable3 + variable4;
0

You are defining your integer inside the if and it is a single line if block, so therefore the variable is just declared and then removed since it runs out of scope -

if ((variable1 - variable) < 0)
     int variable5 = (variable3 + variable4);

Declare it outside -

int variable5 = 0;
if ((variable1 - variable) < 0)
     variable5 = (variable3 + variable4);
0

According to your code, you create a new variable when "if condition" returns true. So as soon as the "block of code of if condition" ends, your block variable "variable5" is destroyed. And so you cannot use it.

Either declare it before your if-condition block and assign it a value in the block OR if you want it to declare within the block of if-condition, Use it inside that block only!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.