我该怎么写这段代码?

时间:2015-03-13 13:31:13

标签: java

    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中没有goto。我可以想到大量复杂的重做方法,但我对编写此代码最干净最推荐的方法感兴趣。

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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);
    }
}