我正在开发一个用于创建老虎机的java程序。该程序按我想要的方式工作,但我不确定我的一个方法调用是否是正确的java礼仪。在下面的main方法中,在for循环中,我在FourTumblers对象机器上调用方法rollAndCompare()。此方法返回一个整数,硬币,表示用户根据匹配的翻转数量赢得多少钱。这个if-else语句是在FourTumblers类中编写的。但是,我还将相同的机器对象作为参数传递,以便该方法可以访问对象的转轮值。有一个更好的方法吗?这是对的吗?
public static void main(String[] args) {
int coins;
int addtLives;
int bank = 0;
int lives = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter how many games you want to play:");
int num = scan.nextInt();
System.out.println("You have decided to play " + num + " games.\n");
for (int i = 1; i <= num; i++) {
FourTumblers machine = new FourTumblers();
coins = machine.rollAndCompare(machine);
bank += coins;
addtLives = coins/100;
lives += addtLives;
System.out.println("You won " + coins + " coins. That's " + addtLives + " lives.");
System.out.println("You now have a total of " + bank + " coins and " + lives + " lives.\n");
}
scan.close();
}
这是我的rollAndCompare方法......
public int rollAndCompare(FourTumblers machine) {
value1 = machine.getValue1();
value2 = machine.getValue2();
value3 = machine.getValue3();
value4 = machine.getValue4();
if ((value1 == value2)&&(value2 == value3)&&(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
System.out.println("Jackpot!");
coins = 600;
return coins;
}
else if (((value1 == value2)&&(value2 == value3))||((value1 == value3)&&(value3 == value4))||((value1 == value2)&&(value2 == value4))||((value2 == value3)&&(value3 == value4))){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 300;
return coins;
}
else if ((value1 == value4)||(value1 == value2)||(value1 == value3)||(value2 == value3)||(value2 == value4)||(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 100;
return coins;
}
else{
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 0;
return coins;
}
}
答案 0 :(得分:0)
您希望在类中添加对象的时间是您要将它与同一类中的其他对象进行比较。
例如:
public class Sample
{
private String name = "Sample Chocolate";
private int cost = 1;
public boolean compareSample(Sample sample)
{
if (sample.name.equals(name) && cost == sample.cost)
return true;
else
return false;
}
然后从另一个班级:
public class SampleTester
{
public static void main(String[] args)
{
Sample sample1 = new Sample();
Sample sample2 = new Sample();
System.out.println("Are sample one and sample two the same?: " + sample1.compareSample(sample2));
}
}
否则你可以简单地在括号内放任何东西:
public boolean compareSample()
{
if (name.equals("Sample Chocolate") && cost == 1)
return true;
else
return false;
}
正如Ashiquzzman雄辩地说:你可以使用this.getValue()调用它,你不需要传递机器(用作machine.getValue()
)。