如何通过方法传递信息并返回值

时间:2014-01-27 19:53:19

标签: java function methods

我是Java的新手,需要帮助。我被要求编写一个掷骰子的程序,并确定玩家在骰子顶面获得两个“1”的机会。我有不同的功能,如role(),getTopFace()等。我想知道骰子上的数字是使用这些函数,但不知道如何在我的main函数中调用它们。这是我的代码:

import javax.swing.JOptionPane;
import java.util.Random;
public class SnakeEyes {

        private final int sides;
    private int topFace;
    public static void main(String[]args)
    {
        String numberSides;
        int n;
        numberSides=JOptionPane.showInputDialog("Please enter the number of sides on the dice:");
        n = Integer.parseInt ( numberSides);

        int[]die=new int[n];
        for (int index=0; index<n;index++)
        {
            die[index]=index+1;
        } 
                //Here is where I want to get information from my functions and calculate the ods of getting two 1's.

    }
    public void Die(int n)
    {
        if(n>0)
        {
            int sides=n;
            topFace=(int)(Math.random()*sides)+1;
        }
        else{
            JOptionPane.showMessageDialog(null,  " Die : precondition voliated");
        }
    }
    public int getTopFace(int topFace)
    {

        return topFace;
    }


    public int role(int[] die)
    {

        topFace=(int)(Math.random()*sides)+1;
        return topFace;

}
}

2 个答案:

答案 0 :(得分:0)

在main方法中创建类SnakeEyes的对象,并使用该对象调用所需的函数。

示例:

SnakeEyes diceObj = new SnakeEyes();
int topFace = diceObj.role(n,....);

答案 1 :(得分:0)

如果你想从main调用这个函数,这个函数必须是“static”,因为main它的静态函数和静态函数只能调用其他静态函数。

但是......对于java程序来说,这是一个非常丑陋的设计,在开始编写java代码之前,你至少需要了解一些关于面向对象的知识。例如,为什么你不能从静态函数调用非静态函数?,这个问题的答案需要有关面向对象的知识,以及如果你想编写严肃的java代码所需要的知识。