Home  >  Article  >  Java  >  What are the common syntax errors when using for loops in Java?

What are the common syntax errors when using for loops in Java?

王林
王林Original
2019-11-27 10:34:523671browse

What are the common syntax errors when using for loops in Java?

The error program 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();
    }
}

Free video tutorial recommendation: java online video

Internal error:

You cannot have a variable declaration in your print statement, write it 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();
    }
}

Another way is to write the declaration on its own line. You have to name it something other than j, because You have declared this variable:

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();
    }
}

In addition, you do not need the Math.pow() method to achieve output:

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();
    }
}

If you want to learn more related knowledge, you can visit :java introductory tutorial

The above is the detailed content of What are the common syntax errors when using for loops in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn