Jeremy Stone
Jeremy Stone

Reputation: 350

How can I restart my java program based on user input?

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



}

}

Upvotes: 0

Views: 3193

Answers (2)

James C. Zhang
James C. Zhang

Reputation: 1

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"));

Upvotes: 0

Aify
Aify

Reputation: 3537

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")){}
}

Upvotes: 5

Related Questions