jeudi 7 octobre 2021

How to search through an array with a random number in Java

For my computer science 3 class, the professor is having us create a Binary tree that consist of random numbers and random operators. I have the random numbers part working, but getting random operators is kinda tricky. I am trying to use a switch-case statement and an array to randomize the operators, but the syntax of this all is quite tricky. Is there a certain why I should go about writing this? Should I even use a switch-case?

import java.util.Random;
public class TestArithmetic {
    public static void main(String[] args) {
            Node n = new Plus(new Divide(randConst(), randConst()),
                    new Divide(randConst(), randConst()));
            Node nDivide = new Divide(new Plus(randConst(), randConst()),
                    new Plus(randConst(), randConst()));
            Node nMulti = new Multi(new Plus(randConst(), randConst()),
                    new Plus(randConst(), randConst()));
            Node nMinus = new Minus(new Plus(randConst(), randConst()),
                    new Plus(randConst(), new Const(4.4)));

            System.out.println(n + " = " + n.eval());
            System.out.println(nDivide + " = " + nDivide.eval());
            System.out.println(nMulti + " = " + nMulti.eval());
            System.out.println(nMinus + " = " + nMinus.eval());
        }
    public static Binop randOp(Node lChild, Node rChild) {
        Node[] opArray = {new Plus(), new Minus(), new Multi(), new Divide()};
        Random randOpNum = new Random();
        int randNumOp1 = randOpNum.nextInt(4);
        
        switch (randNumOp1) {
            case 1:
            case 2:
            case 3:
            case 4:
        }
        return new Binop();
    } 
    
    public static Const randConst() {
        int max = 20;
        int min =1;
        Random num = new Random();
        double randNum = num.nextInt(max-min+1) + min;
        return new Const(randNum);
    }



Aucun commentaire:

Enregistrer un commentaire