mardi 31 juillet 2018

Java, random operator; call the same method into the method

I am trying to learn Java. I have tried to solve a little problem. at this point I dont know what to try anymore. I want to generate 2 random numbers and 2 random operator (+/-). If the result of these is between 0-20 print something, otherwise start over again until the result is in the range. I am getting an error when I recall the method: randomQuestion(); Thanks in advance!

private int randomQuestion(){

    static Random random = new Random();

    //generate 2 random numbers 
    int number = random.nextInt(15)+1;
    int number2 = random.nextInt(15)+1;
    //initiate result 
    int res = 0;
    //operator
    String operator =  randomOperator();

    //if operator is "+" do sum
    //otherwise do subtraction
    if (operator.equals("+")) {
        res = num1+num2;
        return res;
    }
    //if(operator.equals("-")) {
    else {
        res = num1-num2;
        return res;
    }

}

private void checkResult() {
    int res = randomQuestion();
    //if the result is between 0 and 20 (inclusive)
            if (res > 0 && res <= 20) {
                System.out.println(res + " is between 0-20"); 
            }
            else {
                //start over again with new numbers
                randomQuestion();
            }




Aucun commentaire:

Enregistrer un commentaire