java - 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 完成
解决方案
因为String userChoice = null
如果String userChoice == null
while 语句是:
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.");
}
推荐阅读
- json - 对话流向所有平台发送卡片响应
- c# - 如何从 Xamarin Forms 项目中调用 Android 和 iOS 项目中可用的方法?
- sql - string_agg 无法识别内置函数名称 - SQL Server 12.0
- linux - 在 Linux 容器上的 dotnet Core 中实现消息使用者
- c# - 使用单个线程读取特定文件类型
- excel - Excel - 动态高度列上的 SUMPRODUCT
- javascript - 无效的规则结果:Function()
- ios - 根据字典中的日期对字典数组进行排序
- java - 在 Java 中实现多线程堆栈?
- google-cloud-platform - 在 Google Cloud Shell 代码编辑器中禁用 E501 line too long pylint 警告