我是Java的新手,并且不明白我在下面构建此特定程序时收到错误的原因。任何提示/建议将不胜感激!
import java.util.Scanner;
public class Swipe {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Yes or No?");
boolean yes = sc.nextBoolean();
if (yes) {
System.out.println("Congrats!");
}
else {
System.out.println("No match :(");
}
}
}
答案 0 :(得分:2)
sc.nextBoolean();
接受布尔true
和false
而不是Yes
或No
,所以不要使用此消息是或否?< / strong>,我建议将其更改为 true或false?。
或其他选项如果您想使用是或否,您必须使用String
,而不是这样:
String yes = sc.nextLine();
if (yes.equals("Yes")) {
System.out.println("Congrats!");
} else {
System.out.println("No match :(");
}
答案 1 :(得分:0)
您的程序崩溃是因为您输入的"Yes"
无法通过True
方法转换为nextBoolean()
Java数据类型。 "No"
也是如此。
解决方案:始终为True
输入true
或"Yes"
,为False
输入false
或"No"
。我试过这个,它可以在我的机器上运行。
作为替代解决方案,您可以使用@ YCF_L的方法,将您的"Yes"
和"No"
作为字符串进行检查并进行相应的检查。