我在一个低级java类中,我需要使用java和JavaScript创建一个应用程序。我决定创建一个使用加法,减法,乘法和除法创建随机方程的游戏。我遇到的麻烦是我的方程是以字符串的形式创建的,我需要能够计算答案,将其与用户答案进行比较。我以为我的问题有一个下降解决方案,但我一直遇到一些问题。你能帮我吗?我的代码如下:
import java.util.*;
public class GameClient {
private static Stack<String> operations;
private static Stack<Integer> numbers;
private static String[] tokens;
private static int i;
private static Stack<String> subAdd;
private static Stack<Integer> restOfNumbers;
public static void main(String[] args) {
Random variable = new Random();
int numberOfVariables = variable.nextInt(5)+2; //determines length of equation
String equation = "";
equation = equationGenerator(equation, numberOfVariables, variable);
System.out.println(equation);
System.out.print(calculateAnswer(equation));
}
public static String equationGenerator(String equation, int numberOfVariables, Random variable){
int operation;
int var;
var = variable.nextInt(10)+1;
equation += var;
operation = variable.nextInt(4)+1;
if(numberOfVariables == 1){
equation += " = ";
return equation;
}
if(operation == 1)
{
equation += " + ";
}
else if(operation == 2)
{
equation += " - ";
}
else if(operation == 3)
{
equation += " / ";
}
else if(operation == 4)
{
equation += " * ";
}
return equationGenerator(equation, numberOfVariables-1, variable);
}
public static int calculateAnswer(String equation){
String delims = "[ ]+";
tokens = equation.split(delims);
for(i=0; i< tokens.length; i++) //does all multiplication and division first leaving just addition and subtraction
switch(tokens[i]){
case "0": case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":
int number = Integer.parseInt(tokens[i]);
popOrPush(number);
break;
case "*": case "/": case "+": case "-":
popOrPush(tokens[i], tokens);
}
while(!numbers.empty()){ //flips number and operation stacks to do addition and subtraction in correct order
restOfNumbers.push(numbers.pop());
}
while(!operations.empty()){
subAdd.push(operations.pop());
}
while(!subAdd.empty()){
switch(subAdd.pop()){
case "+":
restOfNumbers.push(restOfNumbers.pop() + restOfNumbers.pop());
case "-":
restOfNumbers.push(restOfNumbers.pop() - restOfNumbers.pop());
}
}
return restOfNumbers.pop();
}
public static void popOrPush(int number){
numbers.push(number);
}
public static void popOrPush(String operation, String[] tokens){
switch(operation){
case "*":
int multipliedValue = numbers.pop();
i++;
multipliedValue = multipliedValue * Integer.parseInt(tokens[i]);
numbers.push(multipliedValue);
case "/":
int dividedValue = numbers.pop();
i++;
dividedValue = dividedValue / Integer.parseInt(tokens[i]);
numbers.push(dividedValue);
case "+": case "-":
operations.push(operation);
}
}
}