Can anyone tell me why my console doesn’t show up as a result of anything?

Asked

Viewed 208 times

0

Receive a value n and print the following table using the structure chaining for:

1
2   4
3   9  27
4  16  64  256
n  n²  n³  ...  n^n

I tried to:

import java.util.Scanner;

public class Questao4 {

    public void Cadeia() {
        Scanner num = new Scanner(System.in);
        System.out.printf("Informe um número: ");
        int n = num.nextInt();

        for (int i = 1; i < n; i++) {
            for (int j = 1; j < n; j++) {

                System.out.println(Math.pow(i,j) + "");
            }
            System.out.println("");
        }

    }

}
  • 1

    I posted a variable response based on your original question. Nothing prevents you from deleting the r and leave the Math.pow inside the print

  • Thank you so much for helping me! :)

  • 1

    @Emersonaraujo is welcome, I’m glad that the answer helped you with your question / problem, take advantage and make the [tour] to know how it works to community.

  • 1

    Good that it was useful, the important thing is that with Edit, you clarified things you wouldn’t give with the original post. When you can, read [help] and [Ask], and always try to elaborate the question with the relevant details, so you can have a quick answer

1 answer

3


I’ve made some corrections and adjustments, and I’ve listed them for you to understand the effects of each change:

  • Changed condition i < n for i <= n so that the number of lines matches the typed;

  • Changed condition j < n for j <= i, to meet the statement;

  • created a variable r to store the result of pow, which is a double;

  • added the variable r in print based on version 1 of the question, with separate calculation;

  • change the println for print in the loop, to avoid skipping line between values;

  • removal of the "" within the println end, it’s unnecessary if you just want the line break.

class Questao4 {
    public void Cadeia() {
        Scanner num = new Scanner(System.in);
        System.out.printf("Informe um número: ");
        System.out.println();

        int n = num.nextInt();
        double r;

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                r = Math.pow(i,j);
                System.out.print(r + "        ");
            }
            System.out.println();
        }
    }
}

See working on IDEONE

  • Thank you very much. It was very enlightening. Thank you msm Tava erring in doing both "for" in function of "n".

Browser other questions tagged

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