我正在学习glassFish安装附带的Java EE7教程。这里也有。该代码存在于glassFish服务器安装目录中
CCD_ 1。
该代码工作正常。当用户正确猜测数字时,它当前显示correct!
,但在游戏结束时不显示failed
。所以我介绍了,只是显示failed
消息的一个小更改。我在代码中的相关更改的正上方添加了注释。
不知怎么的,这种改变并没有起到任何作用。也就是说,在游戏结束时,不显示failed
消息。但游戏照常进行。我想知道为什么这不起作用,以及如何纠正?
感谢
public class UserNumberBean implements Serializable {
private static final long serialVersionUID = -7698506329160109476L;
private int number;
private Integer userNumber;
private int minimum;
private int remainingGuesses;
@Inject
@MaxNumber
private int maxNumber;
private int maximum;
@Inject
@Random
Instance<Integer> randomInt;
public UserNumberBean() {
}
public int getNumber() {
return number;
}
public void setUserNumber(Integer user_number) {
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
public int getMaximum() {
return (this.maximum);
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
public int getMinimum() {
return (this.minimum);
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getRemainingGuesses() {
return remainingGuesses;
}
public String check() throws InterruptedException {
if (userNumber > number) {
maximum = userNumber - 1;
}
if (userNumber < number) {
minimum = userNumber + 1;
}
if (userNumber == number) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Correct!"));
}
//if remainingGuesses is less than or equal to zero, display failed message
//-----------------------------------------------
if (remainingGuesses-- <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
return null;
}
@PostConstruct
public void reset() {
this.minimum = 0;
this.userNumber = 0;
this.remainingGuesses = 10;
this.maximum = maxNumber;
this.number = randomInt.get();
}
public void validateNumberRange(FacesContext context,
UIComponent toValidate,
Object value) {
int input = (Integer) value;
if (input < minimum || input > maximum) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("Invalid guess");
context.addMessage(toValidate.getClientId(context), message);
}
}
}
添加FacesMessage实际上是有效的,问题是您在您的条件中使用了后减量。
顾名思义,后减量是在执行包含后减量的语句后递减的。
这意味着,如果你写:
if (remainingGuesses-- <= 0) {
var remainingGuesses
在评估if条件之后递减。
在您的情况下,当检查最后一个猜测时,remainingGuesses
实际上是1,因此if条件不是true
,并且不会添加消息。
不同的明显解决方案:
if (remainingGuesses-- <= 1) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
或
if (--remainingGuesses <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
或
remainingGuesses--;
if (remainingGuesses <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
另请参阅:
- java中的x++和++x之间有区别吗
- 循环中的i++和++i之间的区别