0

I'm writing a program used to calculate the total sales of employees in a small business, and am trying to figure out how to restart the program based on a user input of y/n. I know that loops are what I need to use here, but need a push in the right direction.

Code:

import java.util.Scanner;
public class calcMain {
    public static void main(String[]args){
        double totalPay = 0, itemOne = 239.99, itemTwo = 129.75, itemThree =  99.95, itemFour = 350.89, commission;
    int weeklyBonus = 200, numSold;
    String employee1, employee2, employee3, employee4, yn;


    Scanner kb = new Scanner(System.in);
    System.out.println("Please enter the salesperson's name: ");
    employee1 = kb.nextLine();

    System.out.println("Please enter the number of Item 1 sold: ");
    numSold = kb.nextInt();
    totalPay += (itemOne * numSold);

    System.out.println("Please enter the number of Item 2 sold: ");
    numSold = kb.nextInt();
    totalPay += (itemTwo * numSold);

    System.out.println("Please enter the number of item 3 sold: ");
    numSold = kb.nextInt();
    totalPay += (itemThree * numSold);

    System.out.println("Please enter the number of item 4 sold: ");
    numSold = kb.nextInt();
    totalPay += (itemFour * numSold);

    System.out.println("The total weekly earnings for " +employee1+ " are: " +totalPay);

    System.out.println("Would you like to input the sales of another employee? (y/n)");
    yn = kb.next();



}

}

1
  • By restart, do you mean quit the program to the OS and then start it again, or do you simply mean to put loop the Java code? Commented Jan 20, 2015 at 17:17

2 Answers 2

5

Put all the code inside a while loop that says while (yn.equalsIgnoreCase("y"))

Don't forget to initialize yn to y!

Second solution:

Modify the code so that it returns a string, and if the user inputs y, return y, or if the user inputs n, return n. Put all that code inside a method (lets call it method x for now)

public static void main(String[] args) {
    while(x().equalsIgnoreCase("y")){}
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would prefer putting all his code in a method and calling that method in a loop. :)
0

Using a do-while loop (while loop should have the same effect) and ask for (y/n) at the end.

Like this: String yn; do { // Your code here // Ask for confirmation } while (yn.equals("y"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.