The program hangs when it arrives at the while

Asked

Viewed 78 times

1

I made a basic program about calculating potentiation, but when it comes to while crash, and until the terminal I have to restart. So I can’t continue the program. I even tried to change the way the scanner looked but I realized it was the while even.

import java.util.Scanner;

   
    int c = 0; //contador
    int p = 1; //potencia

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

    System.out.println("Digite o valor da base:");
    a = input.nextInt();
    System.out.println("Digite o valor do expoente:");
    b = input.nextInt();
   
    while (c != b){
         p = p * a;
         c = c++;
        
        }

    System.out.printf("A potencia de int %d como base e int %d como expoente eh: %d\n",a, b, p);
    input.close();
}

1 answer

3


The biggest problem is that the c++ is already doing the increment in the variable, the ++ is an operator that causes side effect and changes the value of the variable, so the attribution of the result in itself is doing something improper and causing problem.

In fact the code could be better organized and give better names to the variables, so can avoid comments.

Could use a for but I preferred to leave it so because it could be exercise requirement.

import java.util.Scanner;

class Main {
    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Digite o valor da base:");
        int base = input.nextInt();
        System.out.println("Digite o valor do expoente:");
        int expoente = input.nextInt();
        int contador = 0;
        int potencia = 1;
        while (contador != expoente) {
            potencia *= base;
            contador++;
        }
        System.out.printf("A potencia de int %d como base e int %d como expoente eh: %d\n", base, expoente, potencia);
        input.close();
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • On the first line where C++ would not be Java?

  • 1

    No :D Look at the original code of the question, it has a c++ :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.