What is wrong with for loop syntax?

86 views Asked by At

I have this piece of code down here - the PlayingDeck class. It's not done, as you see, but what happens is that on line 17, Right under the for loop, I get an error message saying the PlayingCard declaration and initialization isn't a statement. Why so? When I add the curly brackets to the for loop with just that same statement, the error message disappears. Could someone please explain why? All I need are two brackets, one at the start and one at the end of the for loop...?

Thank you

Code that does not compile --------

public class PlayingDeck {
    static int numberOfCards;

    static {
        numberOfCards = 52;
    }

    PlayingCard[] playingDeckArray;

    PlayingDeck() {
        playingDeckArray = new PlayingCard[numberOfCards];

        for (int currentCardNumber = 0; currentCardNumber > 51; currentCardNumber++)
            PlayingCard currentCard = playingDeckArray[currentCardNumber];
    }

    public static void main(String[] args) {

    }
}

Code that Compiles -----

public class PlayingDeck {
    static int numberOfCards;

    static {
        numberOfCards = 52;
    }

    PlayingCard[] playingDeckArray;

    PlayingDeck() {
        playingDeckArray = new PlayingCard[numberOfCards];

        for (int currentCardNumber = 0; currentCardNumber > 51; currentCardNumber++){
            PlayingCard currentCard = playingDeckArray[currentCardNumber];
        }
    }

    public static void main(String[] args) {

    }
}
2

There are 2 answers

3
Eran On BEST ANSWER

It is not allowed because the declaration of PlayingCard currentCard has no scope if you don't wrap it with braces.

BTW, if you want your loop to do something, you should probably change the condition to currentCardNumber < 51;

0
Choudhury Saadmaan Mahmid On

Your problem is in the for loop

for (int currentCardNumber = 0; currentCardNumber > 51; currentCardNumber++)
            PlayingCard currentCard = playingDeckArray[currentCardNumber];
}

The opening curly brace { is missing.

That's a standard for any language, not only java. Any loop, whether it be for loop, or while loop or do-while loop, or any block like if-else, if-else if- else, switch must have opening and closing curly braces.

Read this for more details: Control Flow Statements in Java

Also read this: Wikipedia - Indent Style