2011-12-12 143 views
1
public void humanPlay() 
{ 
if (player1.equalsIgnoreCase("human")) 
    System.out.println("It is player 1's turn."); 
else 
    System.out.println("It is player 2's turn."); 

System.out.println("Player 1 score: " + player1Score); 
System.out.print("Player 2 score: " + player2Score); 

String eitherOr; 

    do { 
    eitherOr= input.nextLine(); 
    humanRoll(); 
    } while (eitherOr.isEmpty()); 

if (!eitherOr.isEmpty()) 
    humanHold(); 

} 

这是整个方法,我唯一想解决的就是这个。如何将此循环转换为另一种循环,while循环?

 String eitherOr; 
do { 
    eitherOr= input.nextLine();  
    humanRoll(); 
    } while (eitherOr.isEmpty()); 

它接受输入多次,因此需要每次输入,以确定发生了什么,这就是为什么我喜欢的do while循环,但由于它每次初始化至少一次,我得到一个额外的滚动超过需要。

我试图做这种方式,而这种方式的各种变化:

String eitherOr = input.nextLine(); 

while(eitherOr.isEmpty()); 
     humanRoll(); 

这不起作用,因为它没有为输入过再问。如果我尝试把input.nextline();进入while循环,它表示“orOr”没有被初始化,即使我在输入时初始化它,命令行仍保持空白,所以它对我的输入没有任何作用。

回答

4

你有外来分号:

while(eitherOr.isEmpty()); 
    humanRoll();' 

应该是:

while(eitherOr.isEmpty()) 
    humanRoll(); 

本质上你的版本是说什么也不做,而eitherOr.isEmpty()true,所以它永远不会调用humanRoll

+1

那么,好像最后一个小时被浪费在一个半结肠上。谢谢,我有一段时间没有用过while循环。由于这种不幸,我预见我会重读一些章节。大概应该是我检查的第一件事是诚实的。 – Renuz

+0

@ LanceySnr尽管它是一个do while循环,但即使有输入,该代码仍然可以工作,但它仍会创建另一个滚动条。 – Renuz

+0

你有没有用过调试器或类似的东西在输入时检查它的内容?鉴于代码发布,我看不出它如何执行循环。 –

1

如果你的第二代码片段,你正在执行一个空语句作为while循环的一部分

while(eitherOr.isEmpty());//this semicolon is a blank statement 
    humanRoll(); 

,你必须以执行humanRoll作为循环

while(eitherOr.isEmpty()) 
    humanRoll(); 

的一部分删除该分号在旁注中使用假名通常避免这样的小问题

while(eitherOr.isEmpty()) { 
    humanRoll(); 
} 

I在上面的代码中,如果引入了无意的分号,它很容易识别。