从用户那里获取字符输入

时间:2018-10-13 20:54:20

标签: java

我正在尝试输入“是”或“否”(“是”或“否”)的用户输入,但是我一直遇到麻烦。我还必须使小写的y和n起作用。我想知道最好的方法是什么?这是我的程序:

import java.util.Scanner;

public class Homework2 {
    public static void main(String args[]) {
        System.out.println("\nWould you like to see some healthy weight loss guidelines? (Y or N)");

        char decision = (char) System.in.read();

        if (decision.equals("Y")) {
            System.out.println("\nPlaceholder");
        } else if (decision.equals("N")) {
            System.out.println("\n");
            System.out.println("========================================================");
            System.out.println("||                                                    ||");
            System.out.println("||         Thank you From Your Friends At             ||");
            System.out.println("||          Happy Valley Fitness Center!              ||");
            System.out.println("||                                                    ||");
            System.out.println("========================================================");
        } else {
            System.out.println("\nYou did not enter yes or no, program stopping");
            System.out.println("\n");
            System.out.println("========================================================");
            System.out.println("||                                                    ||");
            System.out.println("||         Thank you From Your Friends At             ||");
            System.out.println("||          Happy Valley Fitness Center!              ||");
            System.out.println("||                                                    ||");
            System.out.println("========================================================");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

现在,问题在于您无法在.equals()上呼叫char。取而代之的是从System.in作为String读取并使用方法.equalsIgnoreCase(),这样它将匹配大写的Y / N或小写的y / n:

Scanner in = new Scanner(System.in);       
String decision = in.next();
if(decision.equalsIgnoreCase("Y"))
{
    System.out.println("\nPlaceholder");
}