mercredi 12 décembre 2018

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;
    }
}




Aucun commentaire:

Enregistrer un commentaire