Java初学者匹配程序没有构建

时间:2017-03-11 16:34:12

标签: java android

我是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 :(");
    }
}
}

2 个答案:

答案 0 :(得分:2)

sc.nextBoolean();接受布尔truefalse而不是YesNo,所以不要使用此消息是或否?< / 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"作为字符串进行检查并进行相应的检查。