java - If语句用于处理来自用户的意外响应以猜测数字程序不起作用
问题描述
我目前正在开展一个“猜数字”项目,我的要求之一是处理来自用户的意外输出。我还想知道我应该将这段代码放在代码中的哪个位置,因为我的代码感觉非常杂乱无章。
不是我使用的 if 语句没有编译,我不知道为什么。
while (!text.equals("yes")){
System.out.println("Is your number " + (guess) + "?");
System.out.println("yes,higher,or lower");
text = reader.nextLine();
if (text.equals("higher")){
min = guess + 1;
}
if (text.equals("lower")){
max = guess - 1;
}
guess = (max + min)/2;
if (text.equals("yes")){
System.out.println("Yay! I guessed it.");
}
if (!text.equals("yes" || "higher" || "lower" || "ok")){
System.out.println ("I dont understand " + (text));
System.out.println("Is your number " + (guess) + "?");
System.out.println("yes,higher,or lower");
}
}
期望的输出
Think of a number between 1 and 1000
Type ok when you're ready
ready
You said ready
I guess that means you're ready
Don't forget your number
Is your number 500?
yes, higher, or lower
no
I don't understand no
Is your number 500?
yes, higher, or lower
lower
Is your number 250?
yes, higher, or lower
yes
Yay! I guessed it
=======
//error with my code
exit status 1
Main.java:38: error: bad operand types for binary operator '||'
if (!text.equals("yes" || "higher" || "lower" || "ok")){
^
first type: String
second type: String
1 error
解决方案
您可以将您的 if 条件更改为
text.matches("yes|higher|lower|ok")
推荐阅读
- materialize - Materialise 1.0 中的下拉菜单或下拉菜单
- c# - 运行过程/批量插入时 DataGridView 中的参数超出范围异常
- java - 在 Oracle WebLogic Server 上部署多个版本 .jar
- sql - MERGE 与 WHERE 子句
- css - 我在 F12 开发人员控制台中看到的“normalize.less”是什么?
- javascript - 如何单次搜索来识别一个点值?
- vue.js - 无法在 Ag-grid 中恢复、保存过滤器数据
- python - 从多索引熊猫数据框中选择索引和列的子集
- r - R中从XML到Dataframe的气象数据
- javascript - 性能 - 功能组件内部的功能