2014-11-25 43 views
5

昨天我讀了關於for循環的Java逗號運算符。按我的預期工作。我想到了這種結構,但它沒有像預期的那樣工作。使用逗號運算符{(),{})是否有可能?

';' expected 
     } while((userInput < 1 || userInput > 3), wrongInput = true); 

';' expected 
     } while((userInput < 1 || userInput > 3), wrongInput = true); 

我的想法是,一個迭代後,如果userInput不是1和3之間,它應該下一次迭代將顯示一條錯誤消息時設置布爾wrongInputtrue讓。表示userInput無效。

private int askUserToSelectDifficulty() { 
    int userInput; 
    Boolean wrongInput = false; 

    do{ 
     if(wrongInput) println("\n\t Wrong input: possible selection 1, 2 or 3"); 
     userInput = readInt(); 
    } while((userInput < 1 || userInput > 3), wrongInput = true); 

    return userInput; 
} 

我想,也許是因爲這是在for循環的條件部分的等價內部,這是無效的語法。因爲你不能在條件部分使用逗號運算符?所使用的,我所看到的逗號操作

例子在for循環:Giving multiple conditions in for loop in JavaJava - comma operator outside for loop declaration

+1

看看java運營商 - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – Joseph118 2014-11-25 11:56:02

+1

和那些昏迷的例子被用來分配多個值,但沒有條件 – Joseph118 2014-11-25 11:57:08

+0

@ Joseph118很高興知道NPE已經指出,它不是Java中的運營商。這確實不在文檔中。 – Joop 2014-11-25 12:06:08

回答

1

有在Java中沒有逗號操作者(未在C/C++感反正)。有一些上下文可以用逗號一次聲明和初始化多個事物,但是這並不能推廣到其他上下文中,就像你的例子中的那樣。詞組

一種方式你的循環是像這樣:

while (true) { 
    userInput = readInt(); 
    if (userInput >= 1 && userInput <= 3) { 
     break; 
    } 
    println("\n\t Wrong input: possible selection 1, 2 or 3"); 
}; 
3

這可能是最好解開這一點。

userInput = readInt(); 
while (userInput < 1 || userInput > 3) { 
    System.out.println("\n\tWrong input: possible selection 1, 2 or 3"); 
    userInput = readInt(); 
} 

這可以避免需要標誌。