How to return value from a method

amine dev Source

I'm stuck with this problem in a method. The idea is make a dicerolls counter. I made a function called rolldice(); and I want to use it in the main. I used a while into the main and I want to make a count return, but I don't know where is the problem. Does anyone know it please?

  static int rolldice(){
    double randomnum=Math.random();
    randomnum=randomnum*6;
    randomnum=randomnum+1;
    int randomint =(int) randomnum;
    return randomint;


}
public static int  main(String[] args) {
    int roll1= rolldice();
    int roll2=rolldice();
    int count=1;
    while(!(roll1==roll2)) {
        roll1=rolldice();
        roll2=rolldice();
        count=count+1;

    }
    return count;

}
java

Answers

answered 2 months ago Kristóf Bácskai #1

It doesn't work because the main method is a void so you can't return count with it because it is an int

answered 2 months ago Raj #2

main() method in java can't return a value. Instead of that you can create another method that can return int value as shown here. Now, you can call that method anywhere according to your task and it will return the count value.

static int rolldice(){
    double randomnum=Math.random();
    randomnum=randomnum*6;
    randomnum=randomnum+1;
    int randomint =(int) randomnum;
    return randomint;        
}
public static void main(String[] args) {    

}

public static int roll(){

    int roll1= rolldice();
    int roll2=rolldice();
    int count=1;
    while(!(roll1==roll2)) {
        roll1=rolldice();
        roll2=rolldice();
        count=count+1;

    }
    return count;
}

answered 2 months ago Deadpool #3

A small modification and clean up to your code, as everyone said main will not have return type and it will not return anything, in that case you need to declare your own method with return type and should return from it

public static void main(String[] args) {
int roll1= (int) (Math.random()*6+1);
int roll2= (int) (Math.random()*6+1);
int total=rollDice(roll1,roll2);
System.out.println(total);
 }

 public static int rollDice(int roll1, int roll2) {
    int count=0;
    while(!(roll1==roll2)) {
        roll1=(int) (Math.random()*6+1);
        roll2=(int) (Math.random()*6+1);
        count++;

    }
    return count;
}

comments powered by Disqus