Methods do not work. How to be right?

public class Dice{ public static void main( String[] args){ // constants // variables Die die1; Die die2; die1 = new Die(); die2 = new Die(); } // program code public int rollDice(){ die1.roll(); die2.roll(); return die1.getFaceValue() + die2.getFaceValue(); } public int getDie1FaceValue(){ return die1.getFaceValue(); } public int getDie2FaceValue(){ return die2.getFaceValue(); } public int getDiceTotal(){ return die1.getFaceValue() + die2.getFaceValue(); } public String toString(){ return "Die face number is"; } } 

where, roll () is a method in the Die class that gives a random number from 1 to 6; getFaceValue () is a method in the Die class that returns this number.

  • To test their performance, at a minimum, they need to be called, which you do not do. - post_zeew Nov.
  • one
    And in general, this code will not compile because you are trying to access variables outside their scope. - post_zeew Nov.
  • @post_zeew Methods inside main won't work either. How should I write so that the variables are in the scope of the methods? - user219793
  • You do not need to declare methods inside other methods, they need to be called . Make your objects fields of class. - post_zeew Nov.
  • This is not a workable code. It is difficult to even say exactly what the problem is. I have a feeling that you do not understand some fundamental things - classes, their methods, their fields, scope. I would advise reading some entry level java books. - m. vokhm

1 answer 1

Remove the variables die1 and die2 from the static main method to the fields of the Dice class:

 public class Dice{ Die die1 = new Die(); Die die2 = new Die(); public static void main( String[] args){ // constants // variables Dice dice = new Dice(); System.out.println(dice.rollDice()); } //Другие вспомогательные методы //... }