Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java syntax error while trying to learn for loops

Tags:

java

I am trying to teach myself Java, and am learning about for loops. I am trying to write a short and simple program that gives me the following output:

1

1 4

1 4 9

1 4 9 25

I have a feeling I am getting tripped up in the exponent portion. My source code is as follows:

public class Forloop {
public static void main(String[] args) {
    for (int i = 1; i <= 4; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print(int j = Math.pow(j,i));
        }
    System.out.println();
    }
}

}

Can anyone provide me any help as to where I have gone wrong, and perhaps the fix to it. Much thanks.

like image 430
Rivers31334 Avatar asked Feb 15 '23 01:02

Rivers31334


2 Answers

You can't have a variable declaration in your print statement. Just write like this:

public static void main(final String[] args) {
    for (int i = 1; i <= 4; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print(Math.pow(j, i));
        }
        System.out.println();
    }
}

An alternative would be to write the declaration on it's own line. You would have to name it something other than j though, since you already have that variable declared:

public static void main(final String[] args) {
    for (int i = 1; i <= 4; i++) {
        for (int j = 1; j <= i; j++) {
            int exp = (int) Math.pow(j, i);
            System.out.print(exp);
        }
        System.out.println();
    }
}

Also, as @JigarJoshi points out, you don't need the Math.pow() method to achieve your output, since you are outputting squares. This will do what you are aiming for:

public static void main(final String[] args) {
    for (int i = 1; i <= 4; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print(j * j + " ");
        }
        System.out.println();
    }
}
like image 147
Keppil Avatar answered Feb 23 '23 20:02

Keppil


You can do it like so

public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print((int) Math.pow(j, 2));
            System.out.print(" ");
        }
        System.out.println();
    }
}

Which outputs

1
1 4
1 4 9
1 4 9 16
1 4 9 16 25
like image 35
Elliott Frisch Avatar answered Feb 23 '23 21:02

Elliott Frisch