私は現在Android Studioの学校プロジェクトに取り組んでいますが、これまではボタンを押すたびに「3 + 9/3」のようなランダムな方程式を生成するコードを書いています画面上。この式はテキストビューに表示されます。今度はdoubleを使って "abs"コマンドを使って方程式の結果を評価しようとしました。そのためには、方程式を文字列に格納してから、 "abs"コマンドが文字列をサポートしないため、doubleに変換しようとしました。しかし二重に方程式を保存
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"コマンドを使用できるように、文字列から私の方程式を保存する別の方法はありますか?
何かが私の質問に不明である場合は、AKSへお気軽に、私は、問題を明確にしようとします:)
事前にすでにありがとうございます!
ps。ちょっと前に似たような質問をしましたが、重複していると誤ってマークされています。
方程式は唯一の文字列として保存することができますになります。結果を10進数に変換できますが、その結果を最初に計算する必要があります。おそらく[これは興味のあるかもしれません](http://stackoverflow.com/questions/11993849/android-parse-simple-mathematical-formula-from-string) – musefan
前の質問と同じ要求です。 logcatを追加してください。 –
そしてこの質問はあなたが尋ねた以前の質問とどう違うのですか?それとも古いもの? http://stackoverflow.com/questions/39979079/calculate-the-exact-value-of-an-equation実際に**を解析し、**その文字列を評価する必要があります。あなたはDoubleとしてそれを解析することはできません...私はあなたの以前の質問は正しくフラグが付けられたと信じて –