java - 从 OOP 开始 - 骰子游戏问题
问题描述
您好我正在尝试掌握面向对象的编程(OOP)。我正在制作一个骰子游戏,但我有点卡住了 -
package ch6CLASSES;
import java.util.Scanner;
public class getDie {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("A simple dice game.");
int COUNT =10;
for (int i=0;i<COUNT;i++) {
Die userDie = new Die();
System.out.println("user: "+userDie.getValue());
Die computerDie = new Die();
System.out.println("computer: "+computerDie.getValue());
System.out.println();
}
}
}
所以我有另一堂课,我计算了所有内容 - 但现在我的问题是......在我拥有的 for 循环中,我想计算计算机或用户在每一轮后获胜的次数,有什么帮助吗?
解决方案
首先,您需要有某种方法来确定计算机或用户是否获胜。(由于您正在练习 OOP,因此一种方法可能是最合适的)查看您的代码,看起来每个代码Die
都只有一个值,因此您必须不断重新创建对象。我建议使用一个roll()
返回 1 到 6 之间随机数的方法。这样您就不必在循环的每次迭代中创建新对象。
其次,您需要一种方法来确定用户是否获胜。一种简单的方法是让该方法接受一个int
参数,然后将其与当前Die
对象的值进行比较。这里有一些代码可以让你朝着正确的方向开始:
public int roll() {
//generate random number
}
public boolean wonRoll(int value) {
if(this.getValue() > value) {
return true;
} else {
return false;
}
}
然后在你的循环中:
int computerWins = 0;
int userWins = 0;
Die userDie = new Die();
Die computerDie = new Die();
for (int i=0;i<COUNT;i++) {
System.out.println("user: "+userDie.getValue());
System.out.println("computer: "+computerDie.getValue());
if(userDie.wonRoll(computerDie.getValue()) {
userWins++;
} else {
computerWins++;
}
}
System.out.println("Computer won " + computerWins + " many times");
System.out.println("User won " + userWins + " many times");
推荐阅读
- c++ - (C++) 为什么这个程序在输入无效后停止接受输入?
- javascript - 如何使用 Socket.io 在两个节点服务器之间发送大文件
- python - 使用 jq 通过命令行解析简单的 python JSON 输出 - “不能用字符串索引字符串”
- javascript - Chart.js:在 onRefresh() 方法之外调用方法
- python - 我无法导入照片,因此它会出现在我的应用程序“pyimage1”不存在的按钮上
- java - 当类型为
> - amazon-web-services - 我应该为我的文件使用 s3 存储桶还是应该坚持使用我的 ec2 实例
- javascript - 我正在尝试使用 div 名称作为变量来打开和关闭多个按钮的 div
- java - Collections.unmodifiableCollection 返回值
- ruby-on-rails - 部分填写时将 simple_form 设置为 nil 的 html5 日期