首页 > 解决方案 > Java if/else、while 和用户输入

问题描述

        System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");

        String userChoice = null;

        while ((!userChoice.equals("O")) || (!userChoice.equals("E"))) {

            userChoice = input.nextLine();
        }

        if ( userChoice.equals("O") ) {
            System.out.println(name + " has picked odds! The computer will be evens.");
        } else {
            System.out.println(name + " has picked evens! The computer will be odds.");
        }

干杯,伙计们,

我是 Java 新手,我不知道为什么这不起作用。我想询问用户他的选择,直到他选择“O”或“E”。否则重新询问用户他的输入。因此,我的想法是检查 userChoice 是否不等于“O”或“E”> 再次询问。

预先感谢您的帮助!

运行代码时出现此错误:

让我们玩一个叫“赔率和偶数”的游戏 你叫什么名字?Ron 嗨,Ron,你选哪个?(O)dds 还是 (E)vens?com.ronwalter.Main.main(Main.java:18) 处的线程“main”> java.lang.NullPointerException 中的异常 进程以退出代码 1 完成

标签: java

解决方案


因为String userChoice = null

如果String userChoice == nullwhile 语句是:

while((!null.equals("O")) || (!null.equals("E")))

这就是你得到的原因NullPointerException

解决方案是将 userChoice 设置为空字符串:

    System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");

    String userChoice = "";<-------must set value!!!!

    while ((!userChoice.equals("O")) || (!userChoice.equals("E"))) {

        userChoice = input.nextLine();
    }

    if ( userChoice.equals("O") ) {
        System.out.println(name + " has picked odds! The computer will be evens.");
    } else {
        System.out.println(name + " has picked evens! The computer will be odds.");
    }

推荐阅读