【发布时间】:2021-12-15 18:17:10
【问题描述】:
我正在使用 java 中的计算器。我有一种方法可以将用户输入作为字符串解析为双精度数组。我接受一个字符串,并使用一个以“+”作为分隔符的拆分方法将其转换为双精度数组。此代码仅适用于加法操作。这是代码:
public static double[] parseInput(String input){
// creates a String array that contains the elements of the input without the plus signs
String [] pieces = input.trim().split("\\+");
// creates a double array the same size as the string array previous to this
double[] nums = new double [pieces.length];
// loops through each index of the string array, parses and places the element into the double array
for(int i = 0; i < nums.length; i++){
nums[i] = Integer.parseInt(pieces[i]);
}
// returns the double array
return nums;
}
我还需要让它适用于其他操作,例如减法、乘法等...我还需要让它适用于用户在同一行中执行多个操作时,例如 1+3- 2.
我并不担心其中的数学部分,只担心解析。底线是这样的。我需要创建一个数组,其中包含正在操作的数字以及操作。
如果我们可以让它与数字之间的空格一起工作,那就加分了。此代码目前适用于“1+1”,但适用于“1 + 1”。
提前谢谢你。
【问题讨论】:
-
String::split采用正则表达式。我们可以构造一个正则表达式,根据我们的喜好拆分String。