简体   繁体   English

创建一个基本菜单,为什么我做对了? -Java

[英]Creating a basic menu, why can't I get this right? -Java

I'm taking an Intro to Java class, and I haven't been having any trouble until now.我正在学习 Java 入门课程,直到现在我都没有遇到任何问题。 I don't know if I'm just being a fool and the answer is simple but here goes.我不知道我是否只是个傻瓜,答案很简单,但在这里。

I need to create a simple menu.我需要创建一个简单的菜单。 I prompt the user, and then they enter an integer to choose one option.我提示用户,然后他们输入一个整数来选择一个选项。 But there also needs to be an option to type "X" and exit the program.但是还需要有一个选项来键入“X”并退出程序。

Scanner in = new Scanner(System.in);
    System.out.println("Welcome to the Math Study Guide!");
    System.out.println("Which arithmetic table would you like to use?");
    System.out.println("1) Addition");
    System.out.println("2) Subtraction");
    System.out.println("3) Multiplication");
    System.out.println("4) Division");
    System.out.println("X) Exit the program");
    int input = in.nextInt();


    if (input <= 5 )
        {if (input == 1){System.out.println("Addition");}
        {if (input == 2){System.out.println("Subtraction");}
        {if (input == 3){System.out.println("Multiplication");}
        {if (input == 4){System.out.println("Division");}

    else {System.out.println("You have exited");}

Testing it, whenever I type "X" it shuts down everything and doesn't tell me I've exited.测试它,每当我输入“X”时,它都会关闭所有内容,并且不会告诉我我已经退出。 Is there a general input I can use where you can enter either an int or a String?是否有我可以使用的通用输入,您可以在其中输入 int 或 String?

As already stated in some comments, your probleme is the data-type.正如一些评论中已经指出的那样,您的问题是数据类型。 If someone enters 'X' in the program, it is expected to be an integer value, which it is not.如果有人在程序中输入“X”,它应该是一个整数值,但事实并非如此。

To get your Program working you need to alter your datatype from int to String为了让您的程序正常工作,您需要将数据类型从 int 更改为 String

String input = in.next();

this will get you the input.这将为您提供输入。

Now make a switch/case instead of your if-statements现在做一个 switch/case 而不是你的 if 语句

switch (input) {
    case "1" : System.out.println("Addition");
    break;
    case "2" : System.out.println("Subtraction");
    break;
    deafult: System.out.println("You have exited the program");
    break;
}

If you are not familiar with the switch/case statement: case "1" checks if input equals "1".如果您不熟悉 switch/case 语句:case "1" 检查输入是否等于 "1"。 If true it prints out "Addition", after that it is important to make a break;如果为 true,则打印出“Addition”,之后休息很重要; otherwise it would go on checking if input equals "2" and so on.否则它会继续检查输入是否等于“2”等等。 the default branch is activated if nothing else matches.如果没有其他匹配项,则激活默认分支。 So your program would also write "You have exited the program" if your input was eg "r".因此,如果您的输入是例如“r”,您的程序也会写“您已退出程序”。 If you don't want that, just add another case "x" and write your thing.如果你不想那样,只需添加另一个案例“x”并写下你的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM