September 12, 2012

Access String variable from one if statement in another

Question by user185812

I am new to java coming from C#.

If I have a string that gets set in an “if-statement” is there a way to carry that string’s value to other if statements?

E.g. I set the String hi to carry the text “hello” in an if statement, but now have a completely separate if statement, and would like to use the value set to the String hi in the previous if statement.

My issue is that the veriable can’t be set until certain things in the if statement happen.

if(add.equals(temp)) {
    System.out.println ("What is the first number?");
    numberone = listen.nextDouble ();
    System.out.println ("What is the second number?");
    numbertwo = listen.nextDouble ();
    numberthree = numberone + numbertwo;
    previousproblem = numberthree;
    System.out.println ("The answer is " + numberthree);
}

So later on, in another if statement I, need to reference previousproblem, but it can’t be set until this if statement, as numberthree isn’t set until this statement.

Answer by dasblinkenlight

Java is identical to C# in this respect, all you need to do is declaring the variable outside both if statements, and set its initial value:

String s = null;
if (someCondition) {
    s = "hello";
}
if (anotherCondition) {
    System.out.println("s is "+s);
}

Answer by Starx

Define the string, before you start you if and else sequence.

String str1,str2;
if(true) {
   // ... true part
   str1 = "hello";
} else { 
   // ... false part
}

Now in another If

if(true) {
    str2 = str1; //assign the value of str1 to str2 demonstrating the use str1 in another if
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!