I'd like to modify the condition of the Java infinite repetition calculator.

Asked 2 years ago, Updated 2 years ago, 100 views

The program below is infinite hanbok calculation. I did it as I was taught You don't have to enter the number twice I want to input two at a time and then input the operator immediately to print it out.

And now, it's a repeat sentence that ends when you enter the first number as a fixed number. I want to make it a program that ends when I ask if I will continue at the end of the code and answer N. Where can I change the conditional statement like this?

''' import java.util.Scanner;

public class nuber2 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        double x = 0;
        double y = 0;
        String z = "";

        while (true) {
            System.out.println("Hi, I am really good at math! Put me to the test.");
            System.out.print("Please enter number and then press Enter: ");
            x = scan.nextDouble();

            if (x == 999) {
                System.out.print("Bye bye!");
                return;
            } } else {

                System.out.print("Please enter number and then press Enter: ");
                y = scan.nextDouble();

                System.out.print("Please enter one of the operations +, -, * or / and press Enter:");
                z = scan.next();

                switch (z) {
                case "+":
                    System.out.println( + x + " + " + y + " = " + (x + y) );
                    System.out.println("I'm great at subtraction!\n");
                    break;
                case "-":
                    System.out.println( + x + " - " + y + " = " + (x - y) );
                    System.out.println("I'm great at subtraction!\n");
                    break;
                case "*":
                    System.out.println( + x + " * " + y + " = " + (x * y) );
                    System.out.println("I'm great at subtraction!\n");
                    break;
                case "/":
                    System.out.println( + x + " / " + y + " = " + (x / y) );
                    System.out.println("I'm great at subtraction!\n");
                    break;
                default:
                    System.out.println ("Invalid operator".\n");
                } } }}}

'''

java repeat conditional-statement

2022-09-21 23:19

1 Answers

At the end of the code, I want to make this a program that ends when I ask if I want to continue and answer N. Where can I change the conditional statement like this?

There seems to be an answer you want in the question.

It seems better to declare the variable z as char and use it.

Also, if you divide it by 0, an error will occur, so please use the try-catch statement.


2022-09-21 23:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.