Home > Java > Javagetting Started > body text

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

王林
Release: 2019-11-27 10:34:52
Original
3734 people have browsed it

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

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

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

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template