【发布时间】:2016-03-03 03:57:58
【问题描述】:
我是新手,如果我有点困惑,很抱歉
这是我的代码,它是一款基于 2 名玩家的游戏,将 1 或 2 加到变量“计数器”中,最后一个 1 或 2 将所有数字加到 21 获胜。
所以我想得到帮助的是我想锁定用户输入,使其只能选择 1 或 2,而不是其他任何东西,因为这会违反游戏规则。另外我想有一种方法来确定谁赢了,玩家 1 或玩家 2。就像计算循环发生的次数一样,我可以区分玩家 1 还是玩家 2。
任何帮助将不胜感激!谢谢!
package hemtenta;
import java.util.Scanner;
public class Hemtenta {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
int addcounter = 0;
int sum;
System.out.println("Welcome to 21");
System.out.println("The game revolves about you or your opponent getting to 21 ");
System.out.println("You both start on the same number 0, ");
System.out.println("adding 1 or 2 to see which one of you will put the final number adding it all up to 21 and winning.");
System.out.println("Think smart!");
while(counter <= 20) {
System.out.println("Please choose to add 1 or 2");
addcounter = input.nextInt();
counter += addcounter;
System.out.println("We are now on a total of " + (counter));
}
if (counter==21) {
System.out.println("Congratulations x! you won");
}
else {
System.out.println("Something went wrong! Try again");
}
}
}
【问题讨论】:
-
从用户那里获取输入,使用'if condition'检查,如果为真则获取输入,否则就中断。
标签: java if-statement while-loop counter