2016-11-07 160 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); 
}