2016-11-07 110 views
0

我想让一个程序根据小时变量将字符串s1等于某些文本。问题是当我运行程序s1没有找到。我刚开始使用Java,所以我不确定这是否真的效率低下,或者如果它简单,我错过了。变量没有被if语句定义

代码:

public class Main { 

    public static void main(String[] args) { 
     // String Change Test 
     int[] arr; 
     arr = new int[2]; 
     arr[0] = 1; 
     boolean b1 = arr[0] > 1; 
     boolean b2 = arr[0] < 1; 
     boolean b4 = 0 > arr[0]; 
     boolean b3 = b4 && b2; 
     boolean b5 = b1 || b3; 
     if (b5) { 
      String s1 = "You have played for " + arr[0] + " hours!"; 

     } 
     else if (arr[0] == 1) { 
      String s1 = "You have played for 1 hour!"; 

     } 
     else if (arr[0] == 5) { 
      String s1 = "You have not played at all!"; 
     } 
     else { 
      String s1 = "Memory Error in arr[0], Are the hours negative? Is it there?"; 
     } 
     System.out.print (s1); 
    } 
} 
+4

您需要声明的条件范围之外S1。 –

+0

请首先在外部声明变量if语句并在任何地方使用相同的变量。请阅读并理解变量的范围。 –

回答

2

一个变量的范围是其中变量声明该块。块从开始的大括号开始,并停在匹配的大括号大括号处。所以你声明了三个不同的变量,这些变量在其块之外是不可见的(这就是为什么Java允许你用相同的名字声明它三次)。

声明变量一次,块之外:

String s1; 
if (b5) { 
    s1 = "You have played for " + arr[0] + " hours!"; 
} 
... 
0

您需要定义字符串S1在main方法的开头,因为这样的:

 String s1; 

以后,当您设置s1(在你的if,else语句中),你可以这样写:

 s1 = "You have played for......"; 

这样,s1将被声明为t代码的开始。

+0

说法s1需要在main方法的开始处声明,但它会起作用,可能给人错误的印象。 –

+0

是的,的确如此。我应该提到一些关于范围的内容。谢谢。 – Abdulgood89

0

代码块内部会发生什么,停留在该代码块中。如果您在if block中声明变量,则在if block之外不可见 - 即使在else ifelse的情况下也不是。你的代码不应该编译,因为最后的s1之前没有声明。

String s1; 
    if (b5) { 
     s1 = "You have played for " + arr[0] + " hours!"; 

    } 
    else if (arr[0] == 1) { 
     s1 = "You have played for 1 hour!"; 

    } 
    else if (arr[0] == 5) { 
     s1 = "You have not played at all!"; 
    } 
    else { 
     s1 = "Memory Error in arr[0], Are the hours negative? Is it there?"; 
    } 
    System.out.print(s1); 

这应该正常工作。

2

试试这个..

int[] arr; 
arr = new int[2]; 
arr[0] = 1; 
boolean b1 = arr[0] > 1; 
boolean b2 = arr[0] < 1; 
boolean b4 = 0 > arr[0]; 
boolean b3 = b4 && b2; 
boolean b5 = b1 || b3; 
String s1 = ""; 
if (b5) { 
    s1 = "You have played for " + arr[0] + " hours!"; 

} 
else if (arr[0] == 1) { 
    s1 = "You have played for 1 hour!"; 

} 
else if (arr[0] == 5) { 
    s1 = "You have not played at all!"; 
} 
else { 
    s1 = "Memory Error in arr[0], Are the hours negative? Is it there?"; 
} 
System.out.print (s1); 
}