为什么这会在收到值之前终止? (Java)的

时间:2010-03-26 21:20:35

标签: java methods while-loop

这是相关的代码段。

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 ; 

}

作为一条额外的信息,checkColor只是检查以确保它的第一个参数,一个字符串,是第二个参数的一个索引中的一个字符串,一个数组。

在我看来,当while方法从键盘获取一个字符串,然后只有当该字符串检出时才是真,而while允许终止。

我得到的输出是:

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

(最后有空格输入输入)

这似乎表明while在输入输入之前终止,因为第一行文本在while内,而第二行文本在它之外。

为什么会这样?

4 个答案:

答案 0 :(得分:11)

因为您将===混淆了吗?

答案 1 :(得分:6)

因为你需要使用

while (a == false)

while (!a)

代替。

('='是赋值运算符。'=='是比较运算符。在这种情况下,您需要使用比较运算符。)

答案 2 :(得分:2)

您需要使用==而不是=来进行'等于'比较。

要么

while (a == false)

while (!a)

会奏效。 !a表示不是。

答案 3 :(得分:1)

即使问题已通过之前的答案解决,我建议将休息条件重写为显式中断。

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

或者编写代码更像是用英语描述的代码。 “在满意之前要求新答案”。

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

代码的意图以这种方式更清晰imho。

相关问题