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.
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();
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With