Java 从主方法到子程序

Java 从主方法到子程序,java,subroutine,Java,Subroutine,我写了我的代码,它完全可以工作,但我没有写我自己的方法。作业的重点是练习使用子程序,这就是我必须使用的。我读了很多关于制作我自己的方法的书。但是我还是不能把我的思想集中在它上面 这是我的一段代码。你能帮我解释一下我是如何用它创建自己的方法并调用它的吗 public static void main(String[] args) { //Display welcome message System.out.println("Welcome to the Math Function

我写了我的代码,它完全可以工作,但我没有写我自己的方法。作业的重点是练习使用子程序,这就是我必须使用的。我读了很多关于制作我自己的方法的书。但是我还是不能把我的思想集中在它上面

这是我的一段代码。你能帮我解释一下我是如何用它创建自己的方法并调用它的吗

public static void main(String[] args) {
    //Display welcome message 
    System.out.println("Welcome to the Math Functions event!");
    Scanner keyIn = new Scanner(System.in);
    Scanner userInput;
    System.out.print("Press the ENTER key to toss the dice.");
    keyIn.nextLine();

    //roll dice
    Random rand = new Random();
    int tries = 0;

    int sum = 0;
    while (sum != 7 && sum != 11) {
    // roll the dice once
    int roll1 = rand.nextInt(6) + 1;
    int roll2 = rand.nextInt(6) + 1;
    sum = roll1 + roll2;
    System.out.println(roll1 + " + " + roll2 + " = " + sum);
    tries++;
    }
}

任何帮助都将不胜感激!谢谢大家!

下面是一个随机掷骰子的方法示例:

public static int rollDice()
{
    Random rand = new Random();
    int roll = rand.nextInt(6) + 1;
    return roll;
}
您可以这样调用函数:

int roll = rollDice();
因此,它可以像这样集成到您的程序中,例如:

public static void main(String[] args) {
    //Display welcome message 
    System.out.println("Welcome to the Math Functions event!");
    Scanner keyIn = new Scanner(System.in);
    Scanner userInput;
    System.out.print("Press the ENTER key to toss the dice.");
    keyIn.nextLine();


    int tries = 0;

    int sum = 0;
    while (sum != 7 && sum != 11) {
    // Here is where you call your newly created method
    int roll1 = rollDice();
    int roll2 = rollDice();
    sum = roll1 + roll2;
    System.out.println(roll1 + " + " + roll2 + " = " + sum);
    tries++;
    }
}
这个想法是,你想把一个复杂的任务分成许多更小的任务。这样,调试就容易多了。以上只是一个例子,但是如果你正在执行一个你意识到是重复的操作,那么一个功能永远不会受到伤害

试着用以下方式思考您的功能:

1。我的功能是什么?

2。它应该向我提供什么数据?

3。我的职能部门向我提供此数据的最低要求是什么?

对于注释中提到的计算字符串字符数的函数:

  • 函数对字符串中的字符进行计数
  • 它提供给您的数据只是一个数字
  • 你只需要一个字符串就可以得到这个数字
  • 根据这些信息,我们可以提出以下功能协议:

    public static int countCharacters(String myString)
    {
        int count = myString.length();
        return count;
    }
    

    返回类型和值是一个
    int
    ,因为这是它需要提供给您的,而
    myString
    是函数工作所需的唯一数据。这样做会使代码更易于维护,您可以将复杂的任务分解为几个非常简单的步骤。

    谢谢!非常彻底。我尝试了你写的随机掷骰子和另一个(void方法),NetBeans写了一个错误——找不到符号,符号:变量rand,位置:class。它为什么这么做?@Salma这很可能意味着你没有申报兰德。在使用之前,请执行以下操作:Random rand=new Random()@萨尔玛:如果你还有问题,把你所有的代码都发给我。这将更容易知道到底是什么问题。它工作得非常好。。。但现在我在其他方面遇到了困难。我需要创建一个方法来计算字符串中的字符数。它在主方法中工作得非常好,但我需要将它用作一种方法。