2011-04-29 60 views
0

以下代码声称使用具有标志的do循环重复输入,直到获得有效的int。关于此Java代码段的问题

do 
{  
    try 
    { 
    // attempt to convert the String to an int 
    n = Integer.parseInt(s); 
    goodInput = true; 
    } 
    catch (NumberFormatException nfe) 
    { 
    s = JOptionPane.showInputDialog(null, 
      s + " is not an integer. Enter an integer"); 
    } 
} while (!goodInput); 

我对这里的逻辑有点困惑。如果刚刚的Integer.parseInt正常工作,或没有异常的现象发生,那么“goodInput”被指定为“true”在

goodInput = true; 

线接!goodInput将被评估为假,因此而循环将继续。这在我看来与设计逻辑矛盾,即在执行正确的解析操作后while循环应该停止。我上面的分析有什么问题。

回答

5

do { } while(x);环路,而x == true,即直到x == false

因此,do { } while(!x);循环而x == false,即直到xtrue

0

如果它解析正确,goodInput为true,这将使!goodInput为false,因此循环将结束。

1

do/while循环的行为与正常的while循环完全相同,但保证至少运行一次。用这些术语来思考它是最好的。

0

当条件(在本例中为!goodInput)计算结果为false时,do-while将停止循环。只要它是真的,它就会继续循环。

3

然后!goodInput将被评估为False,所以while循环会再次继续。

否 - 当表达式计算结果为false时,循环停止。

试着像普通英语一样阅读:“do(stuff)while(expression)is true”。

0

对你的所有分析都是正确的。正如你所说,只有当while statement evaluationfalse时,它才会再次循环。

0

!goodInput必须是false来终止循环。如果goodInput为真,则!goodInput为假,因此循环终止。