简单的输入限制问题

时间:2017-11-13 15:58:38

标签: java

我有一个程序,首先我需要输入命令 - help,以及为什么选择2个命令 - exp或sum等等。首先,应该总是输入帮助,但是我无法输入帮助,但是我可以立即输入exp或sum,如何进行通知,这样如果我输入exp或sum,控制台写信给我:输入help命令第一

我的代码:

import utils.Calculator;

import java.util.Scanner;

public class Never {

    public static final String STOP = "-stop";

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter command: for the initial operation of the program, type "help");
        String word = scan.nextLine(); 

        while (!word.equals(STOP)) {  
            switch (word) {

                case "help": {
                    System.out.println("exp - outputs the root of a number");
                    System.out.println("sum - displays the sum of two numbers");
                }
                break;
                case "exp": {
                    long result = Calculator.exp(scan.nextInt()); 
                    System.out.println(result);
                }
                break;
                case "sum": {
                    System.out.println("Enter first number");
                    int first = scan.nextInt();
                    System.out.println("Enter second number");
                    int second = scan.nextInt();


                    long result = Calculator.sum(first, second);


                    System.out.println(result);

                }
                break;
                default: {
                    System.out.println("Now exit programm");
                }

            }

            word = scan.nextLine(); 

        }

    }

}

1 个答案:

答案 0 :(得分:1)

在第一个do-while循环之前放置一个while循环:

Scanner scan = new Scanner(System.in);
String word;
do {
    System.out.println("Enter command: for the initial operation of the program, type "help");
    word = scan.nextLine(); 
} while(!word.equals("help"));

// the rest of the code

这样程序会检查很多次,直到用户输入帮助