Unsure of how to call my method to be run from main() with a switch statement

Problem: I’m relatively new to Java, and I’m trying to understand how to call a class (or are classes methods?) to the main class to be executed. Also will my System.out message be printed from where it is? I was trying to place it inside the doubleDice class, but was getting errors.

package dicerolling;
public class DiceRolling {

public static void main(String[] args) {

DoubleDice.doubleRoll();

    }

}

What I hope to get: I’m hoping to get an output from the prompt that rolls the dice, and executes through the switch as well from a separate class.

What I’m getting now: Everything runs fine, but I don’t know how to work with methods outside of the main.

EDIT:

public class DoubleDice {

public static void doubleRoll() {

    int maxNum = 6;
    int randomValue = 1 + (int) (Math.random() * maxNum);
    int randomValue2 = 1 + (int) (Math.random() * maxNum);
    int die1 = (randomValue);
    int die2 = (randomValue2);
    int sum = die1 + die2;

    System.out.println(
            "With a roll of the dice: " + die1
            + " + " + die2 + " = " + sum);

    switch (sum) {
        case 2:
            System.out.println("Snake Eyes!");
            break;
        case 7:
            System.out.println("Craps!");
            break;
        case 12:
            System.out.println("Box Cars!");
            break;

    }
  }
}

What I’m getting now: I’m trying to call the DoubleDice class from a different file, but before I can do that; My system.out and switch statement are now showing errors.

EDIT: Solved!

Thank you for any help you can provide!

Answer

Your main() method does not contain any operators. What it contains is a definition of a local class named doubleDice.

As it contains no operators, nothing happens when main() is run.

You could, for example, move that local class to a top level (that is, create a file named doubleDice.java containing that class definition inside it), and then instantiate it and call its method inside your main():

new doubleDice().combination();

One more thing: according to standard Java naming convention, class names are started with a capital letter, so DoubleDice is preferred to doubleDice as class name.

Leave a Reply

Your email address will not be published. Required fields are marked *