user1977061
user1977061

Reputation:

Generate random math operator in Java

I was wondering how I should initialize int c from the switch statement. I can't figure out how to "extract" the random switch-argument into the final answer. I am a beginner so maybe I am missing something obvious here. Here is the code that I have so far:

import java.util.*;
public class whileTest{
public static void main (String args[]){
    Scanner sc = new Scanner(System.in);

    String a;

        do{

        String operatorSwitch;
        int b;
        int c;

        Random number = new Random();
        int d = number.nextInt(100) +1;
        int e = number.nextInt(100) +1;

        Random operatorChoice = new Random();
        int operator = operatorChoice.nextInt(4);

        switch (operator){

            case 0: operatorSwitch= "+";
                c = d+e;
                break;
            case 1: operatorSwitch= "-";
                c = d-e;
                break;
            case 2: operatorSwitch= "*";
                c = d*e;
                break;
            case 3: operatorSwitch= "/";
                c = d/e;
                break;
            default: operatorSwitch= "";
        }
        System.out.println("What is: "+d+operatorSwitch+e+"?");
        b = sc.nextInt();


        if(b!=c)
            System.out.println("Wrong answer! Right answer is: "+c);
        else{if(b==c)
            System.out.println("Right answer!"+c);
        }
            System.out.println("Continue? y/n");
            a = sc.next();

        }while(a.equals("y"));
    }
}

Upvotes: 2

Views: 18697

Answers (2)

flup
flup

Reputation: 27103

Not sure how pretty you wish to make this but you could write an Operator interface with anonymous subclasses and pick a random index from those.

interface Operator{
    public int operateOn( int a, int b );
    public char getDisplayChar();
}

Operator[] operators = {new Operator(){
        public int operateOn(int a, int b){
            return a + b;
        }

        public char getDisplayChar(){
            return '+';
        }
    }, new Operator(){
        public int operateOn(int a, int b){
            return a - b;
        }

        public char getDisplayChar(){
            return '-';
        }
    } // etc.
    };

Upvotes: 1

Perception
Perception

Reputation: 80633

As a practice, unless you have a good reason not too, you should always explicitly initialize your variables. In this case you want to change this:

String operatorSwitch;
int b;
int c;

To this:

String operatorSwitch = null;
int b = 0;
int c = 0;

The problem with your current code is a compilation one, due to the variable 'c' possibly not being initialized.

Upvotes: 4

Related Questions