If语句在Java中生成null结果

时间:2013-04-14 17:48:59

标签: java

我不想添加所有代码,因为它是我正在制作的游戏。无论如何,我声明了class_Selection和Characterclass。用户输入class_Selection的字符串。 它显示结果,然后进入if语句,在该语句中,它使用相同的输入来决定之后要做什么。我是java的新手,并为此编码,这是我的第一个项目。问题可能很简单。正如你所看到的那样,我将它放在所有大写字母中,因为我听说无论用户如何输入它都是全部大写的,它会接受该密钥,例如:MeLeE,这可能不是真的。 结果产生,因为它正确地通过程序的其余部分甚至显示class_Selection的结果,但是当它到达if语句时它显示为null。

修改的 问题是某种程度上字符类等于null所以当我 的System.out.println(Characterclass); 我收到空了。

我修复了==,谢谢你,但我需要以某种方式修复CharacterClass,结果为null。

编辑问题是,在IF语句中我得到了所有大写的答案,我知道可能有办法做到这一点,但我做得不对。如果我输入右键,如果它是MELEE,我输入MELEE将显示结果。我也想当我做的时候 的System.out.println(Characterclass); ,我没有运行它的方法,所以我要解决这个问题。我得到它来显示奖金。

感谢您提出==问题,我的目标更进了一步。

//班级选择

    System.out.println("Which one did you excel in ( Class )? Melee, Magic, or Archery?"); // Class selection
    String class_Selection; // Hold the class name (make method with this to declare bonuses and things that have to do with the class he chose: such as If ( class_Selection == melee) 
    class_Selection = classSelection.next(); // User enters name of class they want
    System.out.println("You entered: " + class_Selection + (" Is this the class you want?, y or n?"));

    String yOrN;
    yOrN = defaultScanner.next();

    if (yOrN == "n") { // redo if selection is no
        System.out.println("Then which class would you like? Melee, Magic, Archery?");
        class_Selection = classSelection.next();
        System.out.println("You entered: " + class_Selection + (" Is this the class you want?, y or n?"));
        yOrN = defaultScanner.next();


    }else{ // Does nothing if y because the selection is correct
    }

    // Continue after class selection


        System.out.println("Your class is: " + class_Selection); // Final display
        System.out.println("\n");


        // This is where your selection takes effect and displays your bonuses

        if (class_Selection == "MELEE") {
            Characterclass = "melee";
            System.out.println("Melee = +5 Blade, +5 Blunt, +5 Hand-To-Hand, +5 Heavy Armor,");

        }
        if (class_Selection == "ARCHERY") {
            Characterclass = "Archery";
            System.out.println("+10 Archery, + 10 Light Armor");

        }
        if (class_Selection == "MAGIC") {
            Characterclass = "Magic";
            System.out.println(" +10 Arcane, +5 Light Armor");


}
        System.out.println(Characterclass);

}   

}

5 个答案:

答案 0 :(得分:2)

if (yOrN == "n") !!!应为if (yOrN.equals("n")){...}

对于任何Object等式检查,您应该使用Object#equals。对于对象引用相等性检查,您应该使用==

答案 1 :(得分:2)

比较Java中的字符串,使用String.equals();不是==运营商。例如yOrN.equals("n")

==运算符检查两个字符串是否引用相同的String对象。 equals()方法比较两个字符串是否在两个字符串中具有相同的字符。

答案 2 :(得分:0)

使用.equals()比较字符串,而不使用比较引用的==。如果您想要不区分大小写的比较,请使用.equalsIgnoreCase()

答案 3 :(得分:0)

Strings的比较应使用等于

进行
if (yOrN == "n") {
// Code
}

将成为

if (yOrN.equlals("n")) {
// Code
}

答案 4 :(得分:0)

使用:

if (yOrN.equals("n"))

阅读this,了解如何比较字符串。