【问题标题】:How to more efficiently get an input from a user to determine a method to use Java如何更有效地从用户那里获取输入以确定使用 Java 的方法
【发布时间】:2017-11-10 02:26:40
【问题描述】:

我正在编写一个程序来收集员工的名字、姓氏和销售数据。我的所有基础知识都能完美运行,但我有 1 个问题。在我的 while 循环中,我已经对其进行了编程,因此如果用户输入“添加”,那么它将调用我在不同类中创建的方法,并将他们输入的任何数字添加到员工当前的销售总额中。该代码有效,但由于某种原因,当我测试它时,我必须在它运行之前输入两次“add”;无论如何我可以解决这个问题吗?(我在中间省略了一堆代码,因为我觉得这对这个问题并不重要。)

//local constants
    final int QUIT = -1;
    final String ADD = "add";
    final String SUBTRACT = "subtract";

    //local variables
    int soldItems;
    String addition;
    String subtraction;
    String nameFirst;
    String nameLast;



    //while the input is not QUIT
    while(soldItems != QUIT)
    {

        //Clear screen then prompt the user to add or subtract
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        System.out.print(Util.setLeft(35, "Add or Subtract: "));
        addition = Keyboard.readString();
        subtraction = Keyboard.readString();
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        //if the user enters add the program will add to the employee total
        if(addition.equals(ADD))
        {
            info.addition(soldItems);

        }

        //else the program will subtract from the employee total
        else
        {
            info.subtraction(soldItems);
        }

        //Displays the employee information and prompts the user for the next sales figure
        System.out.println(info.toString());
        System.out.println();
        System.out.print(Util.setLeft(40, "Input the next Sales Figure: "));
        soldItems = Keyboard.readInt();

    }//end while

    //clear screen
    System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

    //End of program message and Final employee information
    System.out.print(Util.setLeft(45, "Final Employee Information"));
    System.out.println(info.toString());

【问题讨论】:

    标签: java while-loop addition subtraction


    【解决方案1】:
    addition = Keyboard.readString();
    subtraction = Keyboard.readString();
    

    你不需要使用其中两个,只需使用input = Keyboard.readString();,然后检查输入并进行相应的处理。

    【讨论】:

    • 是的,做到了哈哈我觉得很傻,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2017-09-14
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多