-2
我在一個低級別的java類中,我需要使用java和JavaScript製作應用程序。我決定創建一個使用加法,減法,乘法和除法創建隨機方程的遊戲。我遇到的麻煩是我的等式是以字符串的形式創建的,我需要能夠計算答案以將其與用戶答案進行比較。我認爲我有一個解決我的問題的後裔解決方案,但我不斷收到一些問題。你能幫我嗎?我的代碼如下:int形式的字符串方程式答案
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);
}
}
}
那麼,它是java還是javascript?因爲我有消息給你,它不能同時存在。 (爲什麼添加標籤時不知道它是什麼意思?) –
如果是Java,請查看[this](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression -given-in-string-form)SO答案。 –
這是Java而不是Javascript。 – sydluce