Java 在对象上调用方法,并使用同一对象作为方法的参数

Java 在对象上调用方法,并使用同一对象作为方法的参数,java,methods,Java,Methods,我正在开发一个用于创建老虎机的java程序。该程序按照我希望的方式工作,但我不确定我的方法调用是否正确。在下面的主方法中,在for循环中,我对FourTumblers对象machine调用rollAndCompare()方法。此方法返回一个整数coin,表示用户根据匹配的不倒翁数量赢得的金额。这个if-else语句是在FourTumbler类中编写的。但是,我还将同一个机器对象作为参数传递,以便该方法可以访问该对象的tumbler值。有更好的方法吗?这是正确的吗 public static vo

我正在开发一个用于创建老虎机的java程序。该程序按照我希望的方式工作,但我不确定我的方法调用是否正确。在下面的主方法中,在for循环中,我对FourTumblers对象machine调用rollAndCompare()方法。此方法返回一个整数coin,表示用户根据匹配的不倒翁数量赢得的金额。这个if-else语句是在FourTumbler类中编写的。但是,我还将同一个机器对象作为参数传递,以便该方法可以访问该对象的tumbler值。有更好的方法吗?这是正确的吗

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();
}

如果要将对象与同一类中的其他对象进行比较,则需要将对象添加到类中的自身上

例:

然后从另一个班级:

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雄辩地说:您可以使用这个.getValue()调用它,您不需要传递machine(用作
machine.getValue()
)。

如果您放置
machine.rollAndCompare()
,它应该仍然能够访问machine的值。通过从方法
public int machine.rollAndCompare(fourtumbler machine)
中删除
fourtumbler machine
来尝试它,它应该仍然可以工作。只需将
tumbler
设置为类变量,那么该类的任何成员都可以访问它,而无需将其作为参数传递。因为你现在的设计有点。。。。(困惑?)在rollAndCompare()方法中,我为构成FourTumbler对象的四个tumbler对象中的每一个调用getValue()方法。我需要将machine作为参数传递,以便getValue方法可以访问machine的四个转鼓。您可以使用
this.getValue()
调用它,而不需要传递
machine
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;
}