Search code examples
javaif-statementterminatedice

Terminate program with letter Q


I'd like to terminate the program by typing Q whenever. I can't place it in "diceChosen" because it's an integer. I've tried different things but nothing works for me.

Scanner userInput = new Scanner(System.in);

int wins = 0;
int losses = 0;

int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;

int sum = 0;


System.out.println("Välkommen till spelet 12. Du ska slå 1-3 tärningar och försöka få summan 12...");



for (int counter = 0; counter < 3; counter++) {

    System.out.printf("%nAnge vilken tärning du vill slå[1,2,3](avsluta med q): ");

    int diceChosen = userInput.nextInt();

    if (diceChosen == 1)
        diceOne = (int)(Math.random() * 6) + 1;

    if (diceChosen == 2)
        diceTwo = (int)(Math.random() * 6) + 1;

    if (diceChosen == 3)
        diceThree = (int)(Math.random() * 6) + 1;

    sum = diceOne + diceTwo + diceThree;

    if (sum == 12)
        ++wins;

    if (sum > 12)
        ++losses;


    System.out.printf("%d %d %d sum: %d #vinst: %d #förlust: %d", diceOne, diceTwo, diceThree, sum, wins, losses);
}

Solution

  • Since you can not use try and catch other alternative can be by changing your userInput.nextInt() to userInput.nextLine(); so it can detect when Q is pressed if Q is not pressed then we convert String to int so it can calculate the logic with Integer.parseInt(diceChosen);

    All the code

        while (true) {
                for (int counter = 0; counter < 3; counter++) {
    
                    System.out.printf("%nAnge vilken tärning du vill slå[1,2,3](avsluta med q): ");
    
    
                    String diceChosen = diceChosen = userInput.nextLine();
                    int diceChosenToInteger = 0;
                    if (diceChosen.equalsIgnoreCase("Q")) {
                        System.exit(0);
                    } else {
                        diceChosenToInteger = Integer.parseInt(diceChosen);
                    }
    
    
                    if (diceChosenToInteger == 1)
                        diceOne = (int) (Math.random() * 6) + 1;
    
                    if (diceChosenToInteger == 2)
                        diceTwo = (int) (Math.random() * 6) + 1;
    
                    if (diceChosenToInteger == 3)
                        diceThree = (int) (Math.random() * 6) + 1;
    
                    sum = diceOne + diceTwo + diceThree;
    
                    if (sum == 12)
                        ++wins;
    
                    if (sum > 12)
                        ++losses;
    
    
                    System.out.printf("%d %d %d sum: %d #vinst: %d #förlust: %d", diceOne, diceTwo, diceThree, sum, wins, losses);
    
    
                }
            }
    
        }
       
    }