Home > Enterprise >  How do I make "Impossible" print only when no combination equals X
How do I make "Impossible" print only when no combination equals X

Time:09-17

I will make a program to print all combinations of a b c that are equal to x and if none of the combinations are equal to x will then print "Impossible", but my program always prints "Impossible" at the end, how to solve it?

Scanner input = new Scanner(System.in);
        int a = input.nextInt();
        int b = input.nextInt();
        int c = input.nextInt();
        int x = input.nextInt();

        for (int i = 0; i <= x; i  ) {
            for (int j = 0; j <= x; j  ) {
                for (int k = 0; k <= x; k  ) {
                    if (i * a   j * b   k * c == x) {
                        System.out.println(i   " "   j   " "   k);
                    }
                    else if (i * a   j * b   k * c != x && i == x & j == x && k == x ) {
                        System.out.println("Impossible");
                    }
                }
            }
        }

like this: output of the program

CodePudding user response:

The simpliest way is to add variable of type boolean before loop with value default = false. When if (i * a j * b k * c == x) is true then set this variable to 'true' Then remove elseif from loops and add if statement after all lopps : (your variable is false) print "Impossible".

If any result is displayed in response, it will never be "Impossible" If the condition from the middle of the loop is never met, your variable will keep its initial value and statement print "Impossible"

  • Related