【问题标题】:Creating a new class to run game创建一个新的类来运行游戏
【发布时间】:2013-03-30 18:34:44
【问题描述】:

我创建了一个使用剪刀石头布的课程。

public class RPS {

    private char cAns;

    public RPS()
    {
        reset();
    }

    public String promptShoot()
    {
        return "Rock, Paper, Scissors, Shoot! (r/p/s)\n";
    }

    public void AI()
    {
        double temp = Math.random();
        int num = (int)(temp * 2.99);

        switch(num) 
        {
            case 0: 
                cAns = 'r';
                break;
            case 1:
                cAns = 'p';
                break;
            case 2:
                cAns = 's';
                break;
        }
    }

班级随机选择计算机。然后它使用扫描仪请求人工输入。

    public int shoot(char hAns)
    {
        if(hAns == cAns)
            return 0;
        else if((cAns == 'r' && hAns == 'p')
                || (cAns == 'p' && hAns == 's')
                || (cAns == 's' && hAns == 'r'))
            return 1;
        else
            return -1;
    }

一旦双方都选择了他们的选择,它就会宣布获胜者:

    public String winner(int won)
    {
        if(won == 1)
            return "The human won!!! All hail the human!!!";
        else if(won == -1)
            return "The computer won!!! Humans must die!!!";
        else
            return "Tie!";
    }

    public void reset()
    {
        cAns = 'a';
    }
}

我认为这可行,但我没有意识到我需要创建一个单独的类来运行这个 RPS 类。

到目前为止我有这个

import java.util.Scanner;

public class game
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        RPS choice = new RPS();

        choice.AI();

        System.out.print(choice.promptShoot());
        choice.hAns(scan.nextInt());

        scan.close();
    }
}

我认为这会初始化游戏,但它不起作用。有什么建议或者我可以指出正确的方向吗?

【问题讨论】:

    标签: class methods


    【解决方案1】:

    static 添加到winnershoot 方法。 把它放在最后:

    System.out.println(winner(shoot(scan.nextLine().charAt(0))));
    

    删除choice.hAns(scan.nextInt());

    【讨论】:

    • 我让我的教授帮我上 RPS 课,显然他说我不应该改变任何东西。它应该按照他给我的方式工作。我只是应该创建一个运行游戏的类。我只是困惑,因为我是 java 新手..
    • 好吧,我无法重写所有内容,但您可以通过以下方法修复它:将所有内容放在 main 中,然后在 reset() 之后将其放入 RPS()。然后从 main() 中删除所有内容并放入 new RPS();你可以走了。会有一些小故障,但你会很快解决的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多