H
H
heatherr2020-05-26 23:09:07
Java
heatherr, 2020-05-26 23:09:07

How to subtract from a number in Java so that the result is preserved and subtract the next number from this result?

There is a water tank, for example 1000 ml, and there are 2 cups: the first is 100 ml, the second is 200 ml. Water is scooped out of the tank in different sequences by these cups (at random, without any system: first, second, second, first, etc.), when the tank is empty, the user sees a message that the water has run out. I did the "scooping out" of water through the scanner and if / else (if the user enters the console 1, then the first mug, if 2, then the second). And how to make it so that one common value (a tank of 1000 ml) after scooping out 100 ml, returns a new value and the next mug would be subtracted from the new value? The for loop displays all the values ​​​​at once and is not quite suitable because there are two circles, return stops the program. Maybe there are just some solutions, but I just don't know about them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2020-05-26
@heatherr

And how to make it so that one common value (a tank of 1000 ml) after scooping out 100 ml, returns a new value and the next mug would be subtracted from the new value?

So you assign a new value to a variable that contains information about the tank, inside the loop after scooping out (subtracting) and that's it
. Something like this:
public class Main {

    public static void main(String[] args) {

        int volume = 1000;

        Scanner scanner = new Scanner(System.in);
        System.out.println(
                "Объем бака равен - 1000 мл. \n" +
                        "Введите значение 100 мл. или 200 мл."
        );
        while (volume >= 0) {
            int input = scanner.nextInt();

            if(input > volume) {
                System.out.println("В баке нет такого объема воды!");
                continue;
            } else if(input == 100) {
                volume -= input;
                System.out.println("Остаток в баке: " + volume);
            } else if (input == 200) {
                volume -= input;
                System.out.println("Остаток в баке: " + volume);
            } else {
                System.out.println("Вы ввели недействительное значение!");
            }

            if(volume == 0) {
                System.out.println("Вода в баке закончилась");
                break;
            }

        }

    }

}

In the first if branch, we check whether there is such a volume of water in the tank.
In the second and third branches, we subtract the required volume from the total volume of the tank, respectively.
In the fourth branch, we display a message if a value other than 100 or 200 is entered.
And at the very end, if volume is less than 0, then exit the loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question