【问题标题】:Switch case doesn't print to the console?开关盒不打印到控制台?
【发布时间】:2020-10-10 21:50:21
【问题描述】:
public static void startGame(){
    //int stone = 0, diamond = 0, iron = 0, gold = 0;
    StringBuffer blockys = new StringBuffer("\uD83E\uDDCD ▯▯▯▯▯▯▯▯▯");

    Scanner input = new Scanner(System.in);

   
    System.out.println("\uD83E\uDDCD " + "▯▯▯▯▯▯▯▯▯" + "\n");

    String user = input.next();
    boolean game = true;

    while(game) {
        switch (user) {
           //Code

            case "M":
                System.out.println(mine(blockys));
                user = input.next();
                break;

    }
}

public static StringBuffer mine(StringBuffer blockys){
    addOre(blockys);
    blockys.delete(2, 3);

    int randBlock = (int) (Math.random() * 101) + 0;

    //Code
   
    else{
        //add bomb 5% chance
        blockys.append("\uD83E\uDDE8");
    }


    return blockys;
}



public static void addOre(StringBuffer blockys){
    String str = blockys.substring(2, 3);

    switch(str){
        //Code

        case "\uD83E\uDDE8":
            System.out.println("You mined a bomb! BOOOOOOOM! You died!");
            System.exit(0);
            break;
    }
}

在我的 addOre 方法中,当它到达 case "\uD83E\uDDE8" 时,它不会打印到控制台,也不会终止程序。当它到达案例时,它完全忽略它并且程序继续。我尝试将其设置为失败的默认值,并在案例中尝试了不同的变量,但它从不打印任何内容。如何修复它以使其打印并在之后终止?

【问题讨论】:

    标签: java string methods switch-statement stringbuffer


    【解决方案1】:

    这是一个“长度”问题。

    考虑以下代码:

    public static void main(String[] args) {
        System.out.println("Hello".substring(2, 3).length());
        System.out.println("\uD83E\uDDE8".length());
    }
    

    将输出:

    1
    2
    
    那么问题是什么?

    当你是一个子字符串时,你总是会返回一个长度为 1 的字符串。

    而在另一端,在您的 switch 案例中,您正在尝试测试长度为 2 的字符串。

    1 != 2:条件从未满足

    【讨论】:

    • 你知道为什么 \uD83E\uDDE8 的长度是 2 吗?这是一个表情符号,但只作为一个字符出现。
    • 那是因为你有多个 \u 对应一个 unicode 转义序列。在 Java 中,字符等价于短裤(= 2 字节)。这个表情符号是用 4 字节编码的,对应一个 int(= 4 字节)。你需要比较的是一个code point,看看这个:developers.redhat.com/blog/2019/08/16/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2015-05-04
    • 2016-11-19
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多