开发者

Why does this while terminate before receiving a value? (java)

Here's the relevant code snippet.

public static Territory[] assignTerri (Territory[] board, String[] colors) 
{ 
    for (int i = 0; i<board.length; i++) 
    { 
        // so a problem is that Territory.translate is void fix this. 
        System.out.print ("What team controls ") ; Territory.translate (i) ; System.out.println (" ?") ; 

        boolean a = false ;
        while (a = false) 
        {
            String s = getIns () ;
            if ((checkColor (s, colors)))
            {
                board[i].team = (returnIndex (s, colors)) ;
                a =true ; 
            }
            else 
                System.out.println ("error try again") ; 
        }       
        System.out.print ("How many unites are on ") ; Territory.translate (i) ; System.out.println (" ?") ; 
        int n = getInt () ; 
        board[i].population = n ; 
    }
    return board ; 

}

As an additional piece of infor开发者_高级运维mation, checkColor just checks to make sure that its first argument, a string, is a string in one of the indexes of its second argument, an array.

It seems to me that when the while the method gets a string from the keyboard and then only if that string checks out is a true and the while allowed to terminate.

The output I get though is this:

What team controls Alaska ?
How many unites are on Alaska ?

(there is space at the end to type in an input)

This would seem to suggest that the while terminates before an input is ever typed in since the first line of text is within the while while the second line of text comes after it outside of it.

Why is this happening?


Because you confused = with == ?


Because you need to use

while (a == false)

or

while (!a)

instead.

('=' is the assignment operator. '==' is a comparison operator. You need to use a comparison operator in this instance.)


You need to use == rather than = to make an 'equals' comparison.

Either

while (a == false)

or

while (!a)

will work. !a means not a.


Even though the issue is solved by previous answers, I Would recommend rewriting the break condition as an explicit break.

while (true) 
{
    String s = getIns () ;
    if (checkColor(s, colors))
    {
        board[i].team = returnIndex(s, colors);
        break; 
    }
    System.out.println("error try again"); 
}

Or write the code more like how you would describe it in English. "Ask for a new answer until satisfied".

String s = getIns();
while (!checkColor(s, colors))
{
    // Ask for a new answer until satisfied
    System.out.println ("error try again");
    s = getIns();
}
board[i].team = returnIndex(s, colors);

The intention of the code is more clear this way imho.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜