if(text.contains(authcode) && text.contains("balance")){
String balUser = text.split("]")[0];
event.getSession().send(new ClientChatPacket("/money"));
}
if(text.contains("Balance: $")){
text = text.split(": ")[1];
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
event.getSession().send(new ClientChatPacket("/m " + balUser + text));
}
不幸的是,balUser (在第二个IF语句中)在eclipse中被高亮显示为“无法解析为变量”。我只是想知道我是否在某个地方做了错误的语法。
发布于 2014-08-07 07:59:31
是。balUser
是在if
的作用域中定义的。只需在if
语句之外定义它:
String balUser = null;
if(text.contains(authcode) && text.contains("balance")) {
balUser = ....
}
发布于 2014-08-07 07:59:35
在第一个balUser
语句中声明String
,因此它是本地范围的。
在第一个if
语句之外声明它,并在第二个语句中检查null
,以消除这种情况。
发布于 2014-08-07 07:59:36
变量String balUser
是在一对花括号内声明的,因此它的范围仅限于该代码块。
如果您希望在其他地方知道它,则需要在两个块都可以看到的地方声明它。
就你而言:
String balUser = null; // variable declared here
if(text.contains(authcode) && text.contains("balance")){
balUser = text.split("]")[0]; // remove declaration, just assignation
event.getSession().send(new ClientChatPacket("/money"));
}
if(text.contains("Balance: $")){
text = text.split(": ")[1];
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
event.getSession().send(new ClientChatPacket("/m " + balUser + text));
}
https://stackoverflow.com/questions/25187040
复制