gpt4 book ai didi

java - 没有 if 语句的决定

转载 作者:行者123 更新时间:2023-11-29 09:28:39 25 4
gpt4 key购买 nike

以下是说明:

/*
* Write a method called isGameOver. The method should have three parameters,
* all integers and in this order: the player's score, the number of lives
* the player has remaining, the game level. The method should return true
* if the game is over and false otherwise, according to the following game
* rule. The game continues only when the player has at least one life
* remaining and one of these conditions is met:
* --The player is on level 1 and his/her score at least 1000.
* --The player is on level 2 and his/her score at least 2000.
* --The player is on any level and his/her score at least 3000.
*
* For example, the method call isGameOver(1500, 1, 2) should return true.
*
* DO NOT USE AN IF STATEMENT

这是我的代码:

public static String isGameOver(int score, int lives, int level) {

while (level == 1 && level < 1001)
return "false";

while (level == 2 && level < 2001)
return "false";

while (level == 3 && level < 3001)
return "false";

return "true";
}

显然不行,我就是有这种感觉是因为我用了while循环。如何在不使用 if 语句的情况下做出决定?

最佳答案

如果您想要一个可读的解决方案,那么您几乎可以直接将问题描述转化为代码。

/**
* The game continues only when the player...
**/
private static boolean gameContinues(int score, int lives, int level) {
// has at least one life
boolean stillAlive = lives >= 1;
// is on level 1 and his/her score at least 1000
boolean cond1 = (level == 1 && score >= 1000);
// is on level 2 and his/her score at least 2000
boolean cond2 = (level == 2 && score >= 2000);
// is on any level and his/her score at least 3000
boolean cond3 = score >= 3000;

// return true if has at least one life remaining and one of the conditions is met
return stillAlive && (cond1 || cond2 || cond3);
}

// The function you want just returns the inverse of what is defined
public static boolean isGameOver(int score, int lives, int level) {
return !gameContinues(score, lives, level);
}

关于java - 没有 if 语句的决定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35054414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com