Search code examples
javadice

Java code not working due to "Cannot convert from void to int" error


I'm very new to studying the basics of java at uni and am working on a project to return 6 random dice for each player but am coming across this error on the last line "resultRoll = JOptionPane..." Any help would be appreciated.

public class Dice {
  public static void main(String[] args){
  }
        Dice () {
            Component f = new JFrame();
        
        Random rnd = new Random();
        String resultRoll;

        // values set 1 to 6
        int n1 = 1 + rnd.nextInt(7-1);
        int n2 = 1 + rnd.nextInt(7-1);
        int n3 = 1 + rnd.nextInt(7-1);
        int n4 = 1 + rnd.nextInt(7-1);
        int n5 = 1 + rnd.nextInt(7-1);
        int n6 = 1 + rnd.nextInt(7-1);
        
        resultRoll = JOptionPane.showMessageDialog(f, "Yay! You rolled: " + n1 + n2 + n3 + n4 + n5 + n6);
        
    }
}

Solution

  • You probably want to set resultRoll before displaying the message.

    resultRoll = n1 + " " + n2 + " " + n3 + " " + n4 + " " + n5 + " " + n6;
    JOptionPane.showMessageDialog(f, "Yay! You rolled: " + resultRoll);