mardi 30 mai 2023

How do I call a method in an object without passing a variable that should already be in the object?

I am trying to create a dice rolling program to practice writing a program. I am creating a Dice object. I want to be able to create a die and state the number of sides when I create it. Example Dice d6 = new Dice(6). After that I want to be able to just print out the roll result without needing to specify the number of sides. in the call. Right now I have this... System.out.println(d6.rollDie(6));. I would like to be able to just do System.out.println(d6.rollDie); or System.out.println(d6.rollDie()); Having to specify the number of sides each time I call negates the point of having a sides variable in the object.

This is my current Java code.

//Main.java
public class Main {

    public static void main(String[] args) {
    
        Dice d6 = new Dice(6);
        System.out.println(d6.sides);
        System.out.println(d6.rollDie(6));
    }

}


//Dice.java
import java.util.Random;

public class Dice {
    int sides;
    int roll;

    Dice(int sides) {
        this.sides = sides;
    }


    public int rollDie(int sides) {
        this.sides = sides;
        Random random = new Random();
        int result = random.nextInt(sides + 1) + 1;
    
        return result;
    }

}



Aucun commentaire:

Enregistrer un commentaire