Search code examples
javastringrandommethodsreturn

Keeping a variable when referring to a method multiple times


I need this to print out "N1" and then "N2" in random order. My problem is I don't know how to keep the values (num, and num2) so it doesn't print the same number twice. I don't know how to keep a value for the next time the method is used. Any help is apprectiated :)

import java.util.Random;
public class Testing {
    public static void main(String[] args) {
        System.out.println(random());
        System.out.println(random());
    }
    public static String random() {
        Random rgen = new Random();
        int rNumber;
        int num = 0, num2 = 0;

        do {
            rNumber = rgen.nextInt(2) + 1;
        } while ((rNumber == 1 && num == 1) || (rNumber == 2 && num2 == 1));

        if (rNumber == 1) {
            num = 1;
            return "N1";
        }
        else if (rNumber == 2) {
                num2 = 1;
            return "N2";
        }
        else
            return null;
    }
}

Solution

  • I think you mean that you want to preserve the values of num and num2.
    Remove their declarations from random(), and put these at the class level, before main():

    private static int num = 0;
    private static int num2 = 0;
    

    otherwise this loop:

    do {
        rNumber = rgen.nextInt(2) + 1;
    } while ((rNumber == 1 && num == 1) || (rNumber == 2 && num2 == 1));
    

    does not make sense, since the condition:

    ((rNumber == 1 && num == 1) || (rNumber == 2 && num2 == 1))
    

    would always be false.