簡単な電卓を作成していて、実績のある電卓 WolframAlpha を使用して計算を検証したかったのですが、一貫性の問題がいくつかあります。私はこれをプログラミングして、Android、Java、および XML について詳しく学びます。このコードのほとんどは WolframAlphaSample.java ファイルから直接取得され、必要な「ポッド」(情報) のみを返すように簡略化されています。
ActivityMain.java で、関数 my editText を渡します。
Double wolframAnswer = WolframAlpha.queryInput(editLine.getText().toString());
WolframAlpha.queryInput() では、私のコードは次のようになります。
public static double queryInput(String input)
{
WAEngine engine = new WAEngine();
System.out.println("Wolfram Input: " + input);
// These properties will be set in all the WAQuery objects created from this WAEngine.
engine.setAppID(appid);
engine.addFormat("plaintext");
engine.addIncludePodID("DecimalApproximation");
engine.addIncludePodID("Result");
WAQuery query = engine.createQuery(); // Create the query.
query.setInput(input); // Sets property of the query.
double finalResult = 0.0;
try {
// This sends the URL to the Wolfram|Alpha server, gets the XML result
// and parses it into an object hierarchy held by the WAQueryResult object.
WAQueryResult queryResult = engine.performQuery(query);
//System.out.println(((WAPlainText)(queryResult.getPods()[0].getSubpods()[0].getContents()[0])).getText());
String unroundedResult;
if (queryResult.isError())
{
return 1.0; // error
}
else if (!queryResult.isSuccess())
{
return 2.0; // misunderstood
}
else if(queryResult.getPods().length == 1)
{
unroundedResult = ((WAPlainText)(queryResult.getPods()[0].getSubpods()[0].getContents()[0])).getText();
if (unroundedResult.endsWith("...")) // Remove trailing dots if really long number
{
unroundedResult = unroundedResult.replaceAll("\\.\\.\\.", "");
}
}
else
{
unroundedResult = ((WAPlainText)(queryResult.getPods()[1].getSubpods()[0].getContents()[0])).getText();
}
finalResult = Double.parseDouble(unroundedResult);
} catch (WAException e) {
e.printStackTrace();
}
return finalResult;
}
}
簡単なクエリ (5 + 8) を使用して WolframAlpha.java 内のコンソールからこれを実行すると、問題なく動作します。まったく同じデータを渡す Android アプリから実行すると、キャッチして例外をスローします。2 つの異なる動作が見られる理由がわかりましたか?
小さなメモ: 1.0 と 2.0 を返すことは最善のアイデアではありませんが、double ではないエラーを返す方法がわからず、何が起こっているのかをデバッグしたかったため、スローされました。とにかくその道をたどりませんが、ここに残しました。