-2

I'm trying to create an app that will generate random operands questions by using a switch case.

        MaxDigit = Difficulty.Level;
    Random RandomNumber = new Random();

    //Set the First and Second Number to Random Number
    FNumber = RandomNumber.nextInt(MaxDigit);
    SNumber = RandomNumber.nextInt(MaxDigit);


    Random OperandsChoise = new Random();
    int Operands = OperandsChoise.nextInt(4);

    if ((FNumber / SNumber) >= 1) {
        switch (Operands){

            case 0 :
                this.Answer = this.FNumber + this.SNumber;
                this.QTyoe = FNumber + "+" + SNumber + "=";
                break;

            case 1 :
                this.Answer = this.FNumber - this.SNumber;

                this.QTyoe = FNumber + "-" + SNumber + "=";
                break;

            case 2 :
                this.Answer = this.FNumber * this.SNumber;

                this.QTyoe = FNumber + "*" + SNumber + "=";
                break;

            case 3 :
                this.Answer = (this.FNumber +2) / (this.SNumber +1);

                this.QTyoe = FNumber + "/" + SNumber + "=";
                break;
        }
    }

The MaxDigit is getting integers from another activity called "Difficulty" to let users decide how hard the math question they want to challenge (Easy-9, Medium-99, Hard-999). But somehow the SNumber keeps getting 0 and cashing crash.

Is there any way to set SNumber within the range and make the Answer will not less than 1?

Calvin Lim
  • 19
  • 3
  • Well what is the value of `MaxDigit`? If you want a random number excluding 1 you can just add 1 to your generated number. I would also recommend taking note of Java naming conventions, variables should be in `camelCase`, generally only class names should be in `PascalCase`. – Henry Twist Jul 08 '21 at 14:53
  • 1
    `Random.nextInt(N)` return number from interval `[0, N)` ... to return from interval `[1, N)` you need to select from `[0, N-1)` and add `1` ... [information about braces](https://en.wikipedia.org/wiki/Interval_(mathematics)#Including_or_excluding_endpoints) – Selvin Jul 08 '21 at 14:58
  • @HenryTwist The value of `MaxDigit` will change depending on user difficulty level selection (9, 99, 999). Import from another Activity – Calvin Lim Jul 08 '21 at 15:16
  • @Selvin But I need to import the Maxdigit on other activities, to let users select the difficulty level. I have tried using method like (MaxDigit, MaxDigit+1) and (0, MaxDigit+1) but none of these works. – Calvin Lim Jul 08 '21 at 15:22

1 Answers1

1

I see from your code that both FNumber and SNumber will always be positive. You can clamp the second number to never be smaller than 0, for example:

SNumber = RandomNumber.nextInt(MaxDigit - 1) + 1;

The snippet above will ensure that SNumber will never be greater than MaxDigit while always being greater than or equal to 1.

Blunderchips
  • 534
  • 4
  • 22