2015-03-13 71 views
-5
again: 
     while (!s.hasNextInt()) s.next(); 
     amount = s.nextInt(); 
    if(amount < 0 || amount > numberOfCards) { 
     System.out.println("You need to enter a number between 0 and "+numberOfCards); 
     goto again; 
    } 

它在C#中正常工作,但在Java中没有转到。我可以想到大量复杂的重做方式,但我对什么是最干净的最推荐的编写代码的方式感兴趣。我应该如何编写这段代码?

回答

1

笨的办法:

while (true) { 
    while (!s.hasNextInt()) s.next(); 
     amount = s.nextInt(); 
    if(amount < 0 || amount > numberOfCards) { 
     System.out.println("You need to enter a number between 0 and "+numberOfCards); 
    } else { 
     break; 
    } 
} 
+0

什么是聪明的办法? – CodeCamper 2015-03-13 13:36:41

+0

正确地重写代码。愚蠢的方式==模仿goto(实际上使“强制转到”又名'while(true)'并打破退出永远循环。 – iced 2015-03-13 13:40:49

+0

你可以在你的答案中包含智能方式吗?智能方式: – CodeCamper 2015-03-13 13:41:55

0

把它包在一个循环:

while (amount < 0 || amount > numberOfCards) { 
    while (!s.hasNextInt()) s.next(); 
    amount = s.nextInt(); 
    if(amount < 0 || amount > numberOfCards) { 
     System.out.println("You need to enter a number between 0 and "+numberOfCards); 
    } 
}