J
J
JennyK2021-05-06 18:55:52
Java
JennyK, 2021-05-06 18:55:52

How to terminate a Java program when the user enters the character q anywhere in the program?

The task is to write a simple calculator (number-operation-number-result). The program should run indefinitely if the user enters the correct data, but if the user enters the letter q then the program should terminate (exactly terminate, not notify of an error). Here's what I have so far:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    do {
        System.out.println("Введите число");
        int a = sc.nextInt();
        sc.nextLine();
        System.out.println("Введите операцию");
        String s = sc.nextLine();
        System.out.println("Введите число");
        int b = sc.nextInt();
        if (s.equals("+")) {
            int res = 0;
            res = a + b;
            System.out.println(res);
        }
        char c = s.charAt(0);
        if (c == ('q'))
            break;
       
    } while(true);

Now it works if you enter q instead of a mathematical sign. But how can I make the program exit if the user enters q instead of a number?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Orkhan, 2021-05-06
@JennyK

if (c == ('q'))
            break;

here use not break, but System.exit(0);
https://www.tutorialspoint.com/java/lang/system_ex...

D
Deiwan, 2021-05-07
@Deiwan

Make a label at the end of the program and attach a listener to each input that will implement the
continue label method; And when q is entered anywhere
, the program will skip everything that is and implement what you do in that label .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question