【问题标题】:Save an equation in a double将方程式保存为双精度
【发布时间】: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... 我相信您之前的问题已正确标记

标签: java android string math


【解决方案1】:

我认为问题出在这行

double doubleEquation = Double.parseDouble(equation);

你的“方程”是一个带有操作的String,所以你不能把String解析成double。您必须首先评估您的“方程式”。 为此,您必须遍历String operation 中的每个字符,并且当char 为例如“+”时,您执行加法。 String 不仅会评估为数字本身。 像这样的

double i = Double.parseDouble("1");  

将评估为 1.0

但这会导致错误

double i = Double.parseDouble("1+1");

【讨论】:

  • 有没有其他方法可以存储方程式以便我可以使用“abs”命令?
  • 我不这么认为。无论哪种方式,您都必须评估字符串方程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 2013-08-24
  • 2018-11-12
  • 2023-03-23
  • 2015-09-13
  • 1970-01-01
相关资源
最近更新 更多