【发布时间】:2016-10-14 14:40:57
【问题描述】:
我目前正在 Android Studio 中进行一个学校项目,到目前为止,我已经编写了一个代码,它会在您每次按下屏幕上的按钮时生成一个随机方程,例如“3+9/3”。该等式显示在文本视图中。现在我尝试使用双精度的“abs”命令来评估方程的结果。为此,我将方程存储在一个字符串中,然后尝试将其转换为双精度,因为“abs”命令不支持字符串。 代码如下:
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);
}
但是,当我在模拟器中运行应用程序时,我只会收到一条错误消息“NumberFormatException”。所以我想将我的字符串转换为双精度有问题。我的等式中的引号(例如:“5 * 3 + 6”)是否可能会导致问题? 有没有其他方法可以从字符串中存储我的方程式,以便我可以使用“abs”命令?
如果我的问题有任何不清楚的地方,请随时询问,我会尽力澄清问题:)
提前谢谢你!
ps。不久前我问了一个类似的问题,但它被错误地标记为重复。
【问题讨论】:
-
方程只能存储为字符串。您可以将结果转换为十进制,但您需要先计算该结果。也许this might be of interest
-
与上一个问题相同的请求。请添加logcat
-
这个问题与您之前提出的问题有何不同?还是年长的? stackoverflow.com/questions/39979079/… 您必须实际解析 并评估 字符串。您不能只将其解析为 Double... 我相信您之前的问题已正确标记