0

I have a simple problem with my code, i want the while loop to break if the user inputs "N" at the end of the loop but the loop does not wait for the input. How can i solve this issue?

import java.util.*;

public class simpleCalculator {

static int addition(int x, int y) {
    return (x + y);
}

static int multiplication(int x, int y) {
    return (x * y);
}

static int subtraction(int x, int y) {
    return (x - y);
}

static int division(int x, int y) {
    return (x/y);
}

public static void main(String[] args) {
    while (1 == 1) {
        Scanner sc= new Scanner(System.in);
        System.out.println("Please enter the first number: ");
        int firstNum = sc.nextInt();
        System.out.println("Please enter the second number: ");
        int secondNum = sc.nextInt();
        System.out.println("List of operations: ");
        System.out.println("1 - Addition");
        System.out.println("2 - Subtraction");
        System.out.println("3 - Multiplication");
        System.out.println("4 - Division");
        System.out.println("Please select the number corresponding to requested operation:");   
        int userSelection = sc.nextInt();
        switch(userSelection) {
        case (1):
            System.out.println("Result of your addition: " + addition(firstNum, secondNum));
            break;
        case (2):
            System.out.println("Result of your subtraction: " + subtraction(firstNum, secondNum));
            break;
        case(3):
            System.out.println("Result of your multiplication: " + multiplication(firstNum, secondNum));
            break;
        case(4):
            System.out.println("Result of your division: " + division(firstNum, secondNum));
            break;  
        }
        System.out.println("Do you wish to do another operation? (Y/N)");
        
        String userDecision = sc.nextLine();
        if (userDecision.equals("N")) 
            break;      
    }
}

}

Maeglynx
  • 1
  • 1
  • Advice : **never** use `sc.nextInt()`, always use `Integer.parseInt(sc.nextLine())` when reading one int from a line from user – azro Nov 07 '21 at 16:02

0 Answers0