views:

172

answers:

6

When I am running my code, it always stops at the for loop and skips it.

public void assignCell()
{
    Prisoner prisoner = prisoners.get(id-1);
    for(Cell cell : cells)
    if(cell.isAvailable())
    {
        cell.allocate(prisoner);
        String bunk = null;
        if(cell.isEven())
        {
            bunk = "top bunk of cell";
        }
        else
        {
            bunk = "only bunk of cell";
        }
        System.out.println("\t\t" + prisoner.nameToString() + " is in the " + bunk + cell.toString());
    }

}

How can I fix this so it goes through?

A: 

Make sure cell.isAvailable() returns true when it is supposed to. The only way the loop could appear to be "skipped" is if the collection cells is empty or none of the cells are "available."

erickson
+7  A: 

That would suggest that cells is empty. If it's not, we're just guessing - please post a complete program.

However, I would strongly urge you to add braces around your if statement1:

public void assignCell()
{
    Prisoner prisoner = prisoners.get(id-1);
    for(Cell cell : cells)
    {
        if(cell.isAvailable())
        {
            cell.allocate(prisoner);
            String bunk = null;
            if(cell.isEven())
            {
                bunk = "top bunk of cell";
            }
            else
            {
                bunk = "only bunk of cell";
            }
            System.out.println("\t\t" + prisoner.nameToString() 
                               + " is in the " + bunk + cell);
        }
    }
}

In fact, I'd then try to reduce the nesting, and use the conditional operator too:

public void assignCell()
{
    Prisoner prisoner = prisoners.get(id-1);
    for(Cell cell : cells)
    {
        if(!cell.isAvailable())
        {
            continue;
        }
        cell.allocate(prisoner);
        String bunk = cell.isEven() ? "top bunk of cell" : "bottom bunk of cell";
        System.out.println("\t\t" + prisoner.nameToString() 
                           + " is in the " + bunk + cell);

    }
}

Oh, and you probably want a return or break statement there, otherwise a single prisoner will be assigned to all the available cells. Indeed, that may be happening with your first prisoner: check the output of the program very carefully!


1 Another alternative is just to indent the if statement - but give some indication that you really did mean the if statement to be in the loop. Personally I find it helpful always to use braces, as then you can't accidentally add another statement after the first one which looks like it would be part of the loop, but isn't. Readability is king, IMO.

Jon Skeet
Why would one *strongly* urge anyone else to adhere to his style?
Michael Krelin - hacker
I believe you mean 'for' statement.
hoffmandirt
no, he meant *around* if statement.
Michael Krelin - hacker
@hacker: It's not really an issue of style when the vast majority of competent programmers, in addition to nearly every book on the subject, say that you should use braces in this situation.
Welbog
@hacker: Because it will lead to fewer bugs. It's as simple as that. The current code is horrible - it uses neither braces *nor* indentation to indicate that the `if` statement is within the `for` loop. Just indenting would be another option, but in my experience it's simpler to stick to a rule of "always use braces" and avoid worrying about it when you change from a single-statement loop to a multiple-statement loop, etc.
Jon Skeet
I agree with braces around the "for". With that however, the nesting is a bit deep so I would reverse the logic of the 1st if to reduce the nesting by one level, e.g. if(!cell.isAvailable()) continue;
SingleShot
@hacker: if the OP had used variable names of `l1` and `ll` instead of `prisoner` and `cell`, would you have objected to me strongly recommending that sensible names should be used?
Jon Skeet
@SingleShot: You mean like I did in the second listing? :)
Jon Skeet
Jon, I would. No matter what Welbog says it *is* a matter of style and the majority of incompetent programmers producing majority of bugs do embrace each and every statement. It will *not* lead to fewer bugs. Actually, even indentation will not help. But what struck me as out-of-place was not the idea of braces, but urging to follow your example. jjnguy above also said that "he'd enclose loop in braces". And I would, to tell you the truth ;-)
Michael Krelin - hacker
@hacker: I have absolutely no qualms about urging and strongly encouraging people to follow what I see as best practices. It absolutely *does* lead to fewer bugs, btw - I have seen bugs of scoping which would simply not have happened with braces in the right place. Whether you call it style or best practices, I see nothing wrong with encouraging people to follow a path which is likely to lead to code which is more readable and thus easier to understand and maintain.
Jon Skeet
To give other examples: if someone presented you with code which was formatted into a single line several thousand columns long, are you seriously saying you *wouldn't* urge them to format it? I think it is our *duty* to provide advice where we see others falling into habits which we believe will lead to code which is hard to maintain. Just because you can follow bracing rules and still end up with bad code doesn't mean the bracing rules aren't at least a good *start*.
Jon Skeet
readability outside of corporate environment is also subjective. I, for instance, find the code taking up less vertical space much more readable and find wasting extra line on each curly brace very disturbing (I don't mean saving on the loop, but general habit of dedicating extra line to the brace). And you know what - I've seen this "best practice" lead to *a lot* of bugs concerning the general flow and understanding of one's own program (not to mention my own eyes being hurt). I think that the best practice is letting people write the code they maintain the best.
Michael Krelin - hacker
Well, if someone presented the one-liner to me, I'd prefer to stay away from this code and let this someone maintain it ;-) You're right about the duty - it makes sense. It's just that I had this feeling that you're too eager to perform it ;-) In comparison with the other speaker(s) who expressed the same attritude towards braces, but didn't trigger my rebellious self ;-)
Michael Krelin - hacker
@hacker: If I genuinely thought that giving *no* visual indication that the `if` statement was meant to be in the loop was *actually* the code style that the OP would maintain the best, I wouldn't have said anything. I don't for one minute believe that's the case though. Even outside the corporate environment, I usually write code assuming that someone other than myself will want to read it... and I really don't like dense code with very few spaces. I will accommodate opening braces to end-of-line or new-line according to project style, but there has to be *some* indication of desired nesting.
Jon Skeet
I think we'll have to agree to differ - but if the same situation came up again, I'd act exactly the same way. I have no reservations about encouraging people to write readable code. They don't have to take my advice, but I'm certainly going to offer it.
Jon Skeet
What I meant to say is that there's really-really no universal readability. And, anyway, I'm actually sorry I jumped in. It was something in the wording. Besides, there's an answer down there that *only* suggests embracing the `for` content. Without even touching the matter. That's the extreme the everyday sight of which made me attack you ;-)
Michael Krelin - hacker
I would throw Code Complete 2 at anyone that wrote code like this for a project that I was working on.
hoffmandirt
hoffmandirt, I wouldn't work on a project with anyone throwing anything heavier than exception.
Michael Krelin - hacker
haha That's good stuff
hoffmandirt
@hacker: While there is no *absolute* universal readability, there are certain things which pretty much *everyone* will agree on.
Jon Skeet
@hacker, exceptions *are* heavy
bill weaver
Jon, I'd agree with you on braces. But I often find myself in the situation where I belong to minority. And it often takes considerable effort (and waste thereof) to prove my worthiness and establish my right to have an opinion. And I've seen many *pretty much everyones* being forced out of their habits just for the sake of majority. But I'd rather stop here before someone invokes Godwin's Law ;-)
Michael Krelin - hacker
bill weaver, but there's a catch block-ing the way.
Michael Krelin - hacker
So, assuming one downvote is from hacker: would anyone like to explain the other one?
Jon Skeet
I revoke my downvote. I actually was about to assure you it's not mine, when I found looked up to see it is.
Michael Krelin - hacker
@hacker: Thanks, that's appreciated (although I do take your point; I would personally say that for matters of readability, when I'm in the minority on a team, I'll bow to the wishes of the majority). However, there's still another downvote - that's what I'm confused about. I can't see anything technically *wrong* with my answer, and if there *is* something wrong with it, I'd really like to know about it...
Jon Skeet
But since my comment was upvoted, I think the other one is triggered by similar sentiments.
Michael Krelin - hacker
The problem with bowing to majority is that majority often thinks that code readability is a substitute for ability to read, which it is not.
Michael Krelin - hacker
@hacker: I guess it declares who you work with. Everyone I work with is quite capable of reading - but we debate the most readable form for the majority, and then stick to it consistently.
Jon Skeet
Heh, Jon, I worked with different people and find it best to let everyone figure out what's best for them and be tolerant to things that are best for others. This technique implies sharing your idea of best practices ("I would use braces here"), letting others exercise their ideas ("but if you wouldn't - don't"), letting them share their ideas ("look, by saving vertical space I get better grasp on the big picture) and letting them learn from their mistake ("what did I tell you - you would never screw up here if not your stubborn aversion to braces!").
Michael Krelin - hacker
+2  A: 

Are you sure your collection of cells isn't empty ? I would:

  1. print the number of cells prior to looping (cells.size() if it's a collection, cells.length if it's an array)
  2. print some cell info for each iteration, before you make any checks (clue: override toString() on the cell object and display availability etc.)
Brian Agnew
+7  A: 

Even though the code looks correct, I would enclose the loop in braces. It makes it much easier to read.

Besides that, I would check to make sure that cells has items in it.

jjnguy
A: 

For a start I would put the contents of the for loop into {}

Clinton Bosch
+4  A: 

I'll mention this since no one else has: you should learn how to use the debugger that is bundled with your IDE. It can tell you if your cells array is empty. If you're using Eclipse, there are great debugging tutorial videos available here: http://eclipsetutorial.sourceforge.net/debugger.html

JRL
Good point. A debugger would quickly show you whether the list is empty or there is a missing break statement.
hoffmandirt
amen. These sorts of questions are things that a debugger would address in less than 3 seconds.
Kevin Day