-1

在调用变量时,我很难找到 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 识别布尔表达式中的对象?我究竟做错了什么?

4

4 回答 4

3

目前city的范围仅限于 if 或 else 块。通过在方法级别声明它使其成为局部变量来增加其范围。

公共静态无效主要(字符串[]参数){

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);  
     }
于 2013-04-02T14:16:19.183 回答
2

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);  
        }
于 2013-04-02T14:17:20.720 回答
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")){

    }

}
于 2013-04-02T14:17:59.673 回答
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" ) )
            {

            }

        }
于 2013-04-02T14:19:23.810 回答