I'm currently working on a school project in Android Studio and so far I've written a code which generates a random equation, like "3+9/3", everytime you press a button on the screen. This equation shows up in a textview. Now I tried to evaluate the result of the equation with the "abs" command using a double. For that I stored the equation in a string and then tried to convert it to a double because the "abs" command doens't support strings. Here is the code:
String[] operationSet = new String[]{"+", "-", "/", "*"};
public void generate(View view) {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView);
TextEquation.setText(equation);
String stringResultOfEquation = String.valueOf(equation);
// Calculate the result of the equation
double doubleEquation = Double.parseDouble(equation);
double doubleResult = abs(doubleEquation);
String stringResult = String.valueOf(doubleResult);
TextView textResult = (TextView)findViewById(R.id.textView2);
textResult.setText(stringResult);
}
However, when I run the app in the emulator I just get an error message "NumberFormatException". So I guess there is something wrong with converting my string into a double. Is it possible that the quotation marks at my equation (for example: "5*3+6") cause problems? Is there a different way to store my equation from the string so I can use the "abs" command?
If anything is unclear in my question, feel free to aks and I will try to clarify the problem :)
Thank you already in advance!
ps. I asked a similar question a little while ago but it got falsely marked as a duplicate.