I am having issues with the things the title suggests. I need to tokenize the string, determine the operation in order to solve it, convert the numbers into int types and return the expression.
What exactly am I doing wrong as far as the parsing and tokenizing goes? Everything seemed ok until I tried to use the stringSplit. The only allowed library functions are Integer.parseInt() and split(). There are quite a few things on StackOverflow to help, but none that do not utilize only these two library functions. Here is the code I have thus far:
public static void main(String[] args)
{
String a[] = {"12 + 34", "56 - 78", "99 * 99", "10 / 3"};
stringSplit(a, ',');
}
public static int parseInt(String a)
{
int i;
int sum = 0;
double x = Integer.parseInt(a);
for(i = 0; i < a.length(); i++)
sum = sum + x;
System.out.printf("%s = %d\n", sum);
}
The end result should look something like:
12 + 34 = 46.00
56 - 78 = -22.00
And the like. I am not really looking for the answer. More of a lead to my answer. Thank you in advance for any and all help!
Here is working version of what you seemed to be attempting to do. I split each element of your input array on space (" "), and then extract out two operands and an operator. I also put in a check for dividing by zero.
public static void main(String[] args) throws Exception {
String a[] = {"12 + 34", "56 - 78", "99 * 99", "10 / 3"};
stringProcess(a);
}
public static void stringProcess(String[] a) {
for (int i=0; i < a.length; ++i) {
String[] parts = a[i].split(" ");
double operand1 = Double.parseDouble(parts[0]);
String operator = parts[1];
double operand2 = Double.parseDouble(parts[2]);
double result = 0.0;
switch (operator) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
if (operand2 == 0) {
throw new IllegalArgumentException("Divide by zero!");
}
result = operand1 / operand2;
break;
}
System.out.println(operand1 + " " + operator + " " + operand2 +
" = " + String.format( "%.2f", result));
}
}
Output:
12.0 + 34.0 = 46.00
56.0 - 78.0 = -22.00
99.0 * 99.0 = 9801.00
10.0 / 3.0 = 3.33
As per method syntax.
<Access specifier><modifier><return type><method name>(arguments). If you are giving int as return type your method should return a value, else make the return type as void if you do not need any return value.
public class Test{
public static void main(String[] args) {
String a[] = { "12 + 34", "56 - 78", "99 * 99", "10 / 3" };
parseInt(a);
}
public static void parseInt(String[] a) {
int sum = 0;
for (int i = 0; i < a.length; i++) {
String[] pieces = a[i].split(" ");
if("+".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) + Integer.valueOf(pieces[2]);
}else if("-".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) - Integer.valueOf(pieces[2]);
}else if("*".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) * Integer.valueOf(pieces[2]);
}else {
sum = Integer.valueOf(pieces[0]) / Integer.valueOf(pieces[2]);
}
System.out.println("sum" + sum);
}
}
}
Related
I'm trying to make a program that processes a line of rpn expression through a stack method. The input is a string array that is converted from a string input.
String[] collect = "8 6 + 2 /"; //the
String line; //the inputed line
collect = line.split(" "); //the conversion
System.out.println(stackem(collect)); // calling the stack method for an output method
The problem is that the output is always the operator ate the end of the line, so when I put in the code that checks for malformed expressions it always turns into the error. Basically my input would be like this:
input: 8 6 + 2 /
output: Error: "Expression is malformed"
output (without the error code): /
output (what's supposed to be the output): 7
This is the code for the stack method:
public String stackem(String[] input)
{
Stack<String> stack = new Stack<String>();
int x, y;
String result = "";
int get = 0;
String choice;
int value = 0;
String p = "";
int output;
try
{
for (int i = 0; i < input.length; i++)
{
if (input[i] == "+" || input[i] == "-" || input[i] == "*" || input[i] == "/" || input[i] == "^")
{
choice = input[i];
}
else
{
stack.push(input[i]);
continue;
}
switch (choice)
{
case "+":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x + y;
result = p + value;
stack.push(result);
break;
case "-":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y - x;
result = p + value;
stack.push(result);
break;
case "*":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x * y;
result = p + value;
stack.push(result);
break;
case "/":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y / x;
result = p + value;
stack.push(result);
break;
case "^":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = (int)Math.pow(y,x);
result = p + value;
stack.push(result);
break;
default:
continue;
}
}
output = Integer.parseInt(stack.pop());
}
catch (Exception ex)
{
return "Error: Expression is malformed";
}
return "Result: " + output;
}
Is there any way to fix this issue?
So, The code SHOULD convert currencies, but it doesn't do it correctly. I have a variable k(Croatian kuna... 1 EURO = 7.5 KUNA)which is 1 and for example, if I want to convert 1 euro to 1 dollar, the program multiplies the amount (1) by 7.5, then I have that amount of euros in KUNA, and that Works. But, when I go to divide that result (7.5) with 6.3(1 DOLLAR IS 6.3 KUNA), I get the same number.
import java.util.Scanner;
public class Conv {
private double rez;
private double rez2;
private double svota;
Scanner ul = new Scanner(System.in);
public void PretvorbaInKunu(double y) {
System.out.print("Insert amomunt: ");
svota = ul.nextDouble();
rez2 = svota*y;
}
public void PR2(double x) {
rez = getRez2() / x;
}
public double getRez() {
return rez;
}
public double getRez2() {
return rez2;
}
public double getSvota() {
return svota;
}
}
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
public static void main(String[] args) {
double e = 7.5;
double d = 6.3;
double p = 9.5;
double k = 1.0;
Conv more = new Conv();
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
switch(iz) {
case "e":
more.PretvorbaInKunu(e);
break;
case "d":
more.PretvorbaInKunu(d);
break;
case "p":
more.PretvorbaInKunu(p);
break;
case "k":
more.PretvorbaInKunu(k);
break;
}
System.out.println(more.getRez2());
System.out.print(" To ");
String u = in.next();
switch(u) {
case "e":
more.PR2(e);
case "d":
more.PR2(d);
case "p":
more.PR2(p);
case "k":
more.PR2(k);
}
System.out.println(more.getSvota() + " " + iz + " is " + more.getRez() + " " + u);
}
}
The problem is in your second switch-case statement: You need to add a break at the end of every case.
If you change the class Vjezbica like this it should work:
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
public static void main(String[] args) {
double e = 7.5;
double d = 6.3;
double p = 9.5;
double k = 1.0;
Conv more = new Conv();
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
switch (iz) {
case "e":
more.PretvorbaInKunu(e);
break;
case "d":
more.PretvorbaInKunu(d);
break;
case "p":
more.PretvorbaInKunu(p);
break;
case "k":
more.PretvorbaInKunu(k);
break;
}
System.out.println(more.getRez2());
System.out.print(" To ");
String u = in.next();
switch (u) {
case "e":
more.PR2(e);
break;//added break here
case "d":
more.PR2(d);
break;//added break here
case "p":
more.PR2(p);
break;//added break here
case "k":
more.PR2(k);
break;//added break here
}
System.out.println(more.getSvota() + " " + iz + " is " + more.getRez() + " " + u);
//you should also close the scanner at the end...
in.close();
}
}
First of all - mistake was, as already pointed out by Tobias, the missing "break;"
But there are other mistakes in the code, e.g. Scanner is not closed.
I would also suggest to improve code quality. You could write an enum type that performs just calculation (no input - input should be separated). You can easily define currencies with different enum constructors then.
There was also discussion above if double or BigDecimal should be used. BigDecimal is an "expensive" type. I am wondering if float isn't enough, because currency values usually contain a precision of 2 digits - and if you are not dealing with very high amounts, a 32bit float type should already suffer.
I'd rewrite it as follows:
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
private static enum Currency {
EURO(7.5), KUNA(1), DOLLAR(6.3), P(9.3);
private double cr;
Currency(double conversionRate) {
this.cr = conversionRate;
}
// precision: 2digits
public float fromKuna(double kuna) {
return (int) (((kuna) / cr) * 100) / 100f;
}
public float toKuna(double foreignCurrency) {
return (int) (((foreignCurrency) * cr) * 100) / 100f;
}
}
private static Currency readCurrency() {
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
in.close();
switch (iz) { // no break required when returning directly
case "e":
return Currency.EURO;
case "d":
return Currency.DOLLAR;
case "p":
return Currency.P;
case "k":
return Currency.KUNA;
default:
throw new IllegalArgumentException("invalid input: " + iz);
}
}
private static float readAmount() {
Scanner ul = new Scanner(System.in);
float svota = ul.nextFloat();
ul.close();
return svota;
}
public static void main(String[] args) {
System.out.print(" From ");
Currency c1 = readCurrency();
System.out.print("Insert amomunt: ");
float svota = readAmount();
float amountInKuna = c1.toKuna(svota);
System.out.print(" To ");
Currency c2 = readCurrency();
float amountInC2 = c2.fromKuna(amountInKuna);
System.out.println(svota + " " + c1.toString() + " is " + amountInC2 + " " + c2.toString());
}
}
Not considered: conversion does first convert from X to Kuna, and then from Kuna to Y. In both conversions, we are performing an inprecise rounding (flooring instead of correct rounding, and flooring twice instead of just once).
Based on this suggestion, it would be even better if you calculate a precise conversion rate which allows direct conversion from X to Y in the end, and you perform a round operation on the final result then.
Input from the Java commandline: "4 + 6 + 5 - 5".
Wanted outcome: "is 10".
Actual outcome: "is 5".
class Calculator
{
int v_in1, v_in2, v_in3, v_in4, v_answer, result;
String v_sign1, v_sign2, v_sign3;
public Calculator()
{
}
public void count(String[] args)
{
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+": {
v_answer += v_in1;
break;
}
case "-": {
v_answer -= v_in1;
break;
}
}
}
System.out.print("is " + v_answer);
}
}
There might be some additional problems e.g too many variable declared etc, but what I'm concerned about it the for- if- switch part, I'm unable to pin- point the problem.
Thank you :)
The problem is that you are applying the operation to the previous number, not to the next to come. Instead you should memorize the operator and update the result when you see a number, e.g. like this:
int sign = +1, result = 0;
for (String arg : args) {
switch (arg) {
case "+":
sign = +1;
break;
case "-":
sign = -1;
break;
default:
result += sign * Integer.parseInt(arg);
}
}
This is happening because your last integer wont be taken into account as it is just stored in v_in1, but since there is no +,- so it doesnt get added or subtracted. Try this:
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+":
{
v_answer = v_in1 + Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
case "-":
{
v_answer = v_in1 - Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
}
}
I do not know all requirements for this task, but I recommend to convert the whole expression to postfix notation, then parse it using stack to evaluate the result.
I took a look at your method, and I recommend you simplify your code (something like this for long count(String[] args))
long result = 0; // Note, this shadows your Object's result. I'm not sure why you
// had hard-coded fields like that. I don't think you need them.
// Also, this returns a long.
boolean negative = false;
for (String arg : args) {
String oper = arg.trim();
if (oper.equals("+")) { // Is it a plus sign?
negative = false;
} else if (oper.equals("-")) { // Is it a minus sign?
negative = !negative; // - a negative value is addition
} else {
try {
int i = Integer.parseInt(oper); // Parse the integer
if (negative) {
i = -i;
negative = false;
}
result += i; // add the result
} catch (NumberFormatException nfe) {
System.err.println(oper + " is not +, - or a number");
}
}
}
return result;
This is what worked in the exercise.
class Calculator
{
int v_answer = 0;
int v_in1 = 0;
public Calculator()
{
}
public void count(String args[])
{
System.out.println();
System.out.print("Result of the calculation ");
for(int i = 0; i < args.length; i++)
{
System.out.print(args[i]+ " ");
if(i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
}
if(i == 0)
{
v_answer += Integer.parseInt(args[0]);
}
if(args[i].equals("+"))
{
v_answer += Integer.parseInt(args[i+1]);
}
else if(args[i].equals("-"))
{
v_answer -= Integer.parseInt(args[i+1]);
}
}
System.out.print("is " + v_answer);
System.out.println();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a calculator between fractions and that if the user inputs a +,-,*, or / it will correspond in the case. This is the code I have so far:
import java.util.Scanner;
public class calculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String x,y;
System.out.println("Enter first fraction in a / b form: ");
x = input.nextLine();
System.out.println("Enter operation: ");
char z = input.next().charAt(0);
System.out.println("Enter second fraction in c / d form: ");
y = input.nextLine();
String aString = x.substring(0,1);
String bString = x.substring(4,5);
String cString = x.substring(0,1);
String dString = x.substring(4,5);
int a = Integer.parseInt(aString);
int b = Integer.parseInt(bString);
int c = Integer.parseInt(cString);
int d = Integer.parseInt(dString);
int answer = 0;
switch (z)
{
case '+':
answer = (a/b) + (c/d);
break;
case '-':
answer = (a/b) - (c/d);
break;
case '*':
answer = (a/b) * (c/d);
break;
case '/':
answer = (a/b) /(c/d);
break;
default:
System.out.println("ERROR");
break;
}
System.out.println("Answer = " + answer);
}
}
OUTPUT SHOULD BE
Enter first fraction in a / b form:
1 / 2
Enter operation:
+
Enter second fraction in c / d form:
2 / 5
answer = 9/10
The problem is here
String aString = x.substring(0,1);
String bString = x.substring(4,5);
String cString = x.substring(0,1);
String dString = x.substring(4,5);
a=c and b=d
These two line
String cString = x.substring(0,1);
String dString = x.substring(4,5);
should be
String cString = y.substring(0,1);
String dString = y.substring(4,5);
Before switch print the values of a b c d z then you will come to know about your correctness.
One more thing is, you are doing division of int variables so the result will be in int only.
I suggest you to change the types of a b c d and answer to double and use Double.parseDouble() for converting string to double.
This problem is so suited for OOP, an extra class:
public class Q {
public final int numerator;
public final int denominator;
public static Q valueOf(String representation) {
Pattern pattern = Pattern.compile("([-]?\\d+) *[/:] *([-]?\\d+)");
Matcher matcher = pattern.matcher(representation.trim());
if (!matcher.matches()) {
throw new IllegalArgumentException(
"Not a quotient (like '3/4'): " + representation);
}
int num = Integer.parseInt(matcher.group(1));
int den = Integer.parseInt(matcher.group(2));
return new Q(num, den);
}
public Q(int num, int den) {
if (den < 0) {
den = -den;
num = -num;
}
int c = gcd(Math.abs(den), Math.abs(num));
denominator = den / c;
numerator = num / c;
}
#Override
public String toString() {
return numerator + "/" + denominator;
}
public Q add(Q rhs) {
int c = gcd(denominator, rhs.denominator);
int den = (denominator / c) * rhs.denominator;
int num = numerator * (rhs.denominator / c)
+ rhs.numerator * (denominator / c);
return new Q(num, den);
}
public Q mult(Q rhs) {
int den = denominator * rhs.denominator;
int num = numerator * rhs.numerator;
return new Q(num, den);
}
public static int gcd(int x, int y) {
assert x >= 0 && y >= 0;
while (x != y) {
if (x > y) {
x -= y;
} else {
y -= x;
}
}
return x;
}
}
Using this class several small problematic code parts disappear.
What I am supposed to do is this:Write a program that gives the user 10 random math problems, asks for the answer each time, and then tells the user if they were right or wrong. Each problem should use 2 random numbers between 1 and 20, and a random operation (+, -, *, or /). You will need to re-randomize the numbers for each math problem. You should also keep track of how many problems they get right. At the end, tell the user how many problems they got right and give them a message based on their result. For example, you may say “good job” or “you need more practice.”
So far I am at a loss
import java.util.Scanner;
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
if (operator == 1)
System.out.println("+");
if (operator == 2)
System.out.println("-");
if (operator == 3)
System.out.println("*");
if (operator == 4)
System.out.println("/");
}
}
I mostly need to know how to turn these random numbers and operators into a problem, and how to grade each question to see if they are wrong.
Well, what you need to add is:
to count answers:
a variable that counts correct answers (increment it every time the user answers correctly);
a variable to store current correct answer;
a variable to store current user answer (refresh it every next problem, no need to store it forever, cause in your case only statistics is needed);
a function (let it be called e.g. gradeTheStudent() ) which uses several conditions to decide what to print out according to number of correct answers;
to create a problem:
put problem generation and answer evaluation into a cycle, which repeats 10 times;
in your switch (i.e. when you choose operators) also calculate the correct answer:
switch(operator){
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: ....
case 3: ....
case 4: ....
default: break;
}
don't forget to check if the user entered a number or something else (you could use either an Exception or a simple condition).
So, a "pseudocode"solution for your problem would look something like this:
String[] reactions = ["Awesome!","Not bad!","Try again and you will get better!"]
num1 = 0
num2 = 0
operator = NIL
userScore = 0
userAnswer = 0
correctAnswer = 0
def function main:
counter = 0
for counter in range 0 to 10:
generateRandomNumbers()
correctAnswer = generateOperatorAndCorrectAnswer()
printQuestion()
compareResult()
gradeStudent()
def function generateRandomNumbers:
# note that you have already done it!
def function generateOperatorAndCorrectAnswer:
# here goes our switch!
return(correctAnswer);
def function printQuestion:
print "Next problem:" + "\n"
print num1 + " " + operator + " " + num2 + " = " + "\n"
def function compareResult(correctAnswer):
# get user result - in your case with scanner
if(result == correctAnswer)
print "Great job! Correct answer! \n"
userScore++
else print "Sorry, answer is wrong =( \n"
def function gradeStudent (numOfCorrectAnswers):
if(numOfCorrectAnswers >= 7) print reactions[0]
else if(numOfCorrectAnswers < 7 and numOfCorrectAnswers >= 4) print reactions[1]
else print reactions[2]
General advice: don't try to solve the problem all at once. A good approach is to create small functions, each doing its unique task. The same with problem decomposition : you just should write down what you think you need in order to model the situation and then do it step by step.
Note: as far as I can see from your current function, you are not familiar with object oriented programming in Java. This is why I am not providing any tips about how great it would be to use classes. However, if you are, then please let me know, I will add info to my post.
Good luck!
For example you can use something like that:
public class Problem {
private static final int DEFAULT_MIN_VALUE = 2;
private static final int DEFAULT_MAX_VALUE = 20;
private int number1;
private int number2;
private Operation operation;
private Problem(){
}
public static Problem generateRandomProblem(){
return generateRandomProblem(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
}
public static Problem generateRandomProblem(int minValue, int maxValue){
Problem prob = new Problem();
Random randomGen = new Random();
int number1 = randomGen.nextInt(maxValue + minValue) + minValue;
int number2 = randomGen.nextInt(maxValue + minValue) + minValue;
prob.setNumber1(number1);
prob.setNumber2(number2);
int operationCode = randomGen.nextInt(4);
Operation operation = Operation.getOperationByCode(operationCode);
prob.setOperation(operation);
return prob;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public Operation getOperation() {
return operation;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
And another class for holding operations:
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE;
public double operationResult(int n1, int n2) {
switch (this) {
case PLUS: {
return (n1 + n2);
}
case MINUS: {
return n1 - n2;
}
case MULTIPLY: {
return n1 * n2;
}
case DIVIDE: {
return n1 / n2;
}
}
throw new IllegalArgumentException("Behavior for operation is not specified.");
}
public static Operation getOperationByCode(int code) {
switch (code) {
case 1:
return PLUS;
case 2:
return MINUS;
case 3:
return MULTIPLY;
case 4:
return DIVIDE;
}
throw new IllegalArgumentException("Operation with this code not found.");
}
}
But you not must throw IllegalArgumentException, there are another options for handling unexpected arguments.
Printout the numbers and the operation , read the user input using file IO , and perform your logic of keeping a track of answered questions
Code :
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
if (operator == 1)
operation="+";
if (operator == 2)
operation="-";
if (operator == 3)
operation="*";
if (operator == 4)
operation="/";
System.out.println("Question "+number1+operation+number2);
}
}
Keep a track of result and compare with the user input and verify its right or wrong
public static void main(String[] args) throws IOException{
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
int result=0;
if (operator == 1){
operation="+";
result=number1+number2;
}
if (operator == 2) {
operation="-";
result=number1-number2;
}
if (operator == 3){
operation="*";
result=number1*number2;
}
if (operator == 4){
operation="/";
result=number1/number2;
}
System.out.println("Question "+number1+operation+number2);
String result1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
if(result==Integer.parseInt(result1))
System.out.println("Right");
else
System.out.println("Wrong");
}
Since I do not want to hand you a full solution to this problem, and you seem to have some knowledge in the Java language I will just write down how I would continue/change what you have as a start.
First I would store the result in your operator if statements. Result is an int.
if (operator == 1) {
operation="+";
result=number1+number2;
}
After this I would print the math question and wait for the user to answer.
System.out.println("What is the answer to question: " +number1+operation+number2);
userResult = in.nextLine(); // Read one line from the console.
in.close(); // Not really necessary, but a good habit.
At this stage all you have to do is compare the result with the user input and print a message.
if(Integer.parseInt(userResult) == result) {
System.out.println("You are correct!");
} else {
System.out.println("This was unfortunately not correct.");
}
This solution is more or less psudo code and some error handling (if user enters test in the answer for example) is missing, also I would split it up into methods rather than have it all in main(). Next step would be to make it object oriented (Have a look at the answer from demi). Good luck in finalizing your program.
In regard to generating random math operations with +, -, * & / with random numbers your can try the following;
import java.util.*;
public class RandomOperations{
public static void main(String[] args){
Random `mathPro` = new Random();
//for the numbers in the game
int a = mathPro.nextInt(50)+1;
int b = mathPro.nextInt(50)+1;
//for the all the math operation result
int add = a+b;
int sub = a-b;
int mult = a*b;
int div = a/b;
//for the operators in the game
int x = mathPro.nextInt(4);
/*
-so every random number between 1 and 4 will represent a math operator
1 = +
2 = -
3 = x
4 = /
*/
if(x == 1){
System.out.println("addition");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(add);
}else if(x == 2){
System.out.println("subtraction");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(sub);
}else if(x == 3){
System.out.println("multiplication");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(mult);
}else{
System.out.println("division");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(div);
}
//This os for the user to get his input then convert it to a numbers that the program can
//understand
Scanner userAnswer = new Scanner(System.in);
System.out.println("Give it a try");
int n = `userAnswer.nextInt();