1

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.

4

4 回答 4

2

Java 在这方面与 C# 相同,您需要做的就是在两个 if 语句之外声明变量,并设置其初始值:

String s = null;
if (someCondition) {
    s = "hello";
}
if (anotherCondition) {
    System.out.println("s is "+s);
}
于 2012-09-12T02:15:54.830 回答
0

在开始 if 和 else 序列之前定义字符串。

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

现在在另一个If

if(true) {
    str2 = str1; //assign the value of str1 to str2 demonstrating the use str1 in another if
}
于 2012-09-12T02:17:11.040 回答
0

变量在它声明的范围内可用;一个范围可以很容易地通过封闭来识别{ }

因此,如果您需要跨两个if语句访问变量,则需要在两个语句的范围内声明它们if

if(condition) {

}
if(another condition) {

}

如果您应该在第一个 if 语句之外声明它,则在两者中使用变量,如下所示:

String myVariable = "";

if(condition) {
    //myVariable operation
}
if(another condition) {
    //myVariable another operation    
}
于 2012-09-12T04:23:15.883 回答
0

请参阅简单概念。在方法之后定义变量 =null 喜欢:

Condition =null;

if (Condition == true){
System.out.println(Condition);
else{
System.out.println(Condition);
}

所以现在条件值应该是块的访问外部

于 2015-06-23T06:56:47.307 回答