在调用变量时,我很难找到java正在遇到什么问题。我正在创建一个简单的聊天机器人,这是我到目前为止所做的:
public class Chatbot {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog("Hi! How are you? My name is Chatbot! What is yours? ");
if (name.compareTo("a")<0){
String city = JOptionPane.showInputDialog("Nice to meet you! Where are you from, "+name);
}
else
{
String city = JOptionPane.showInputDialog("Huh. That's a strange name. Where are you from,"+name);
}
if (!city.equals("Seattle")){
}
}
}
我的问题是java不会在if else语句中识别变量city,所以说city不能解析。如何让java识别布尔表达式中的对象?我做错了什么?
答案 0 :(得分:3)
目前city
的范围仅限于if或else block。通过在方法级别声明它来使其成为局部变量来增加其范围。
public static void main(String [] args){
String name = JOptionPane.showInputDialog("Hi! How are you? My name is Chatbot! What is yours? ");
String city="";
if (name.compareTo("a")<0){
city = JOptionPane.showInputDialog("Nice to meet you! Where are you from, "+name);
}
else
{
city = JOptionPane.showInputDialog("Huh. That's a strange name. Where are you from,"+name);
}
答案 1 :(得分:2)
Decalre String city = null
位于顶部。然后使用它。它必须超出if else
块。
String city=null;
String name = JOptionPane.showInputDialog("Hi! How are you? My name is Chatbot! What is yours? ");
if (name.compareTo("a")<0){
city = JOptionPane.showInputDialog("Nice to meet you! Where are you from, "+name);
}
else
{
city = JOptionPane.showInputDialog("Huh. That's a strange name. Where are you from,"+name);
}
答案 2 :(得分:0)
如前所述,您需要在if-else块之外声明city,如下所示:
public static void main(String[] args) {
String name = JOptionPane.showInputDialog("Hi! How are you? My name is Chatbot! What is yours?");
String city = null;
if (name.compareTo("a")<0){
city = JOptionPane.showInputDialog("Nice to meet you! Where are you from, "+name);
}
else
{
city = JOptionPane.showInputDialog("Huh. That's a strange name. Where are you from,"+name);
}
if (!city.equals("Seattle")){
}
}
答案 3 :(得分:0)
尝试追随希望它有所帮助。
public static void main( String[] args )
{
String name = JOptionPane.showInputDialog( "Hi! How are you? My name is Chatbot! What is yours? " );
String city = "";
if ( name.compareTo( "a" ) < 0 )
{
city = JOptionPane.showInputDialog( "Nice to meet you! Where are you from, " + name );
}
else
{
city = JOptionPane.showInputDialog( "Huh. That's a strange name. Where are you from," + name );
}
if ( !city.equals( "Seattle" ) )
{
}
}