Java 如何通过方法传递信息并返回值
我是Java新手,需要帮助。我被要求编写一个程序来掷骰子,并确定玩家在骰子顶面上得到两个“1”的几率。我有不同的函数,如role()、getTopFace()等。我想知道骰子上的数字是多少,但不知道如何在我的主函数中调用它们。这是我的密码:Java 如何通过方法传递信息并返回值,java,function,methods,Java,Function,Methods,我是Java新手,需要帮助。我被要求编写一个程序来掷骰子,并确定玩家在骰子顶面上得到两个“1”的几率。我有不同的函数,如role()、getTopFace()等。我想知道骰子上的数字是多少,但不知道如何在我的主函数中调用它们。这是我的密码: import javax.swing.JOptionPane; import java.util.Random; public class SnakeEyes { private final int sides; private i
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;
}
}
import javax.swing.JOptionPane;
导入java.util.Random;
公营蛇{
双方的私人谈判;
私人int-topFace;
公共静态void main(字符串[]args)
{
字符串编号;
int n;
numberSides=JOptionPane.showInputDialog(“请输入骰子的边数:”);
n=整数.parseInt(numberSides);
int[]模具=新的int[n];
对于(int index=0;index在main方法中创建类的对象SnakeEyes
,并使用该对象调用所需的函数
例如:
SnakeEyes diceObj = new SnakeEyes();
int topFace = diceObj.role(n,....);
如果要从main调用此函数,则此函数必须是“静态”的,因为main是静态函数,静态函数只能调用其他静态函数
但是……对于java程序来说,这是一个非常难看的设计,在开始编写java代码之前,你需要至少了解一点面向对象的知识。例如,为什么不能从静态函数调用非静态函数?这个问题的答案需要关于面向对象的知识,如果你愿意的话,这是你需要的知识编写严肃的java代码。为什么role()
函数采用topFace
参数?很抱歉,这实际上是一个输入错误。您能帮我解决问题吗?私有final int-sides;
从未初始化(在构造函数中)。所以它的值始终为0。我知道这是一个丑陋的设计,但我被赋予了结构。我不允许构建自己的结构,这就是为什么我发现很难理解。你可以将此方法设置为静态,顺便向提供此“结构”的人推荐阅读有关OO的内容。