Search code examples
javawhile-loopadditionsubtraction

How to more efficiently get an input from a user to determine a method to use Java


I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have 1 issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total. The code works, but for some reason when I test it I have to enter "add" twice before it runs; is there anyway I can fix this?(I left out a bunch of code in the middle as I feel it wasn't important to this question.)

//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());

Solution

  • addition = Keyboard.readString();
    subtraction = Keyboard.readString();
    

    You dont need to use two of them, just use input = Keyboard.readString(); and then check the input and process it accordingly.