2014-01-27 47 views
0

我是Java新手,需要帮助。我被要求编写一个掷骰子的程序,并确定玩家在骰子上面获得两个“1”的机会。我有不同的功能,如角色(),getTopFace()等我想要得到骰子上使用这些函数的数字,但不知道如何在我的主函数中调用它们。这里是我的代码:如何通过方法传递信息并返回值

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; 

} 
} 
+0

为什么'role()'函数需要'topFace'参数? –

+0

对不起,这实际上是一个错字。你能帮助解决我的问题吗? – user3241910

+0

'private final int sides;'永远不会初始化(在构造函数中)。所以它的价值永远是0. –

回答

0

,让您的主要方法你SnakeEyes类的对象,并使用该对象调用所需的功能。

例子:

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

如果要调用这个函数从主这个功能必须是“静态的”,因为它的主要一个静态函数和静态函数只能调用其他的静态函数。

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

+0

我知道这是一个丑陋的设计,但我被赋予了结构。我无法组建自己的结构,这就是为什么我发现很难理解。 – user3241910

+0

你可以使这个方法是静态的,并通过建议阅读关于OO的方式给那个给你这个“结构”的人。 – AlfredoCasado