2015-06-18 63 views
0

我正在製作一個IRC bot。如果有人輸入「!tell username:message」,我希望能夠查看用戶是否在線。下面是我的代碼,它看起來穿過通道,並檢查用戶的第一部分,如果用戶已經在網上:當我有這個在NetBeans如何正確使用這個布爾值?

if (messageIC.startsWith("!tell ")) { 
    boolean userIsOnChannel; 
    String messagey = message.substring(6); 
    String[] messager = messagey.split(":"); 
    String username = messager[0]; 
    User[] users = getUsers(channel); 
    for (final User user : getUsers(channel)) { 
     if (user.getNick().equalsIgnoreCase(username)) { 
      userIsOnChannel = true; 
      sendMessage(channel, username + " is online now!"); 
      break; 
     } 
     else { 
      userIsOnChannel = false; 
     } 
    } 

} 

所以,它告訴我,該變量userIsOnChannel是從未使用過。我以爲我在if/else語句中使用了它。這會產生問題,因爲我希望能夠存儲用戶的消息,並且如果布爾值返回false,則可以沿着「我將該消息傳遞給」通道的方式發送一些消息給通道。當我嘗試使用布爾值時,我得到一個從未初始化的錯誤。我做錯了什麼?

+1

它已設置,但從未閱讀。 – EJP

+0

@EJP當我嘗試使用它時,我收到一個錯誤,它可能沒有被初始化。 – quibblify

+0

你只是初始化不使用它。在第2行初始化它。 – Jack

回答

5

只要代碼塊完成,該變量就會超出範圍。你「使用」它通過設置它,但你永遠不使用它作爲一個布爾(你從來沒有檢查該值。

你可能需要改變

if (messageIC.startsWith("!tell ")) { 
boolean userIsOnChannel; 

boolean userIsOnChannel = false; 
if (messageIC.startsWith("!tell ")) { 

所以userIsOnChannel在該代碼塊之後可用

您得到「may not hav Ë被初始化」,因爲它不只是寫

boolean userIsOnChannel; 

你需要給它分配一個值(在這種情況下可能假)得到的值..

+0

for循環也可能不會迭代,變量也不會初始化。 – 1010

2

如果默認布爾值是‘假’然後將其初始化爲false並刪除else塊。

if (messageIC.startsWith("!tell ")) { 
    boolean userIsOnChannel = false; 
    String messagey = message.substring(6); 
    String[] messager = messagey.split(":"); 
    String username = messager[0]; 
    User[] users = getUsers(channel); 
    for (final User user : getUsers(channel)) { 
     if (user.getNick().equalsIgnoreCase(username)) { 
      userIsOnChannel = true; 
      sendMessage(channel, username + " is online now!"); 
      break; 
     } 

    } 

} 
0

您需要有東西使用或返回該字段。

如果爲字段添加getter方法,警告應該消失。

getUserIsOnChannel(){ 
return userIsOnChannel; 
} 
0

在這裏,我將嘗試用簡單的話通過評論來解釋它。

boolean userIsOnChannel; 
// at this place userIsChannel is undefinded and definitely you will 
// try to get its value. 
for(....) { 
    if(condition) { 
     userIsOnChannel = ... 
    } else { 
     userIsOnChannel = ... 
    } 
    // Here you will not get any error if you use userIsOnChannel 
    // because it is obvious that if if statement is not satisfied 
    // then else will be and userIsOnChannel will definitely be assigned. 
} 
// But here you will again get error because it compiler again here cannot 
// confirm that the userIsOnChannel has a value (may be for statement not run even 1 time 

所以你必須在使用它之前初始化你的變量,編譯器可以確認它的值將被賦值。

相關問題