现在,我有一个程序,把一个输入的表达式到后缀评估。下面是我的控制台的副本。
Enter an expression: ((5*2-1)/6+14/3)*(2*3-5)+7/2
5 2 * 1 - 6 / 14 3 / + 2 3 * 5 - * 7 2 / + 现在我需要遍历输出,但是这个输出只是System.out.print的一堆,我尝试使用一个stringBuilder,但是它无法区分14和1和4。
不管怎么说,我可以检查这个输出的每一个字符吗?我需要把这些数字放进一堆。
发布于 2014-10-09 20:30:11
您可以使用String.split(),如果只需要数字正则表达式。
以下是一个例子:
public class Test {
public static void main(String[] args) {
String str = "1 * 2 3 / 4 5 6";
String[] arr = str.split(" ", str.length());
for (int i=0;i < arr.length;i++)
System.out.println(arr[i] + "is diggit? " + arr[i].matches("-?\\d+(\\.\\d+)?"));
}
}斯塔尔握着长长的绳子。arr将保存拆分的子字符串。
您只需确保每个子字符串的一个空格与另一个空间不同。
发布于 2014-10-09 20:26:23
嗯,你在我读的时候删除了你的代码,但这是一个概念上发展出来的答案。
当您输入每个字符时,您希望将其推到堆栈中。
您提到的唯一场景14是唯一的,因为它是两个字符。
所以你要做的是跟踪最后一个字符是否也是一个数字。
这是一个粗糙的假象。您的堆栈应该都是String来支持这一点。
//unique case for digit
if(s.charAt(0).isDigit()) {
//check to see if the String at the top of a stack is a number by peeking at its first character
if(stack.peek().charAt(0).isDigit()) {
int i = Integer.parseInt(stack.pop()) * 10;
//we want to increment the entire String by 10, so a 1 -> 10
i = i + Character.getNumericValue(s.charAt(0)); //add the last digit, so 10 + 4 = 14
stack.push(Integer.toString(i)); //put the thing back on the stack
}
else {
//handle normally
stack.push(s.substring(0,1));
}
}发布于 2014-10-09 20:22:24
您需要解析实际字符串有什么原因吗?
如果是这样的话,那么您所做的就是创建一个StringBuffer或StringBuilder,在代码中放置System.out.print的地方,附加缓冲区--包括空格,这将帮助您区分14到14。然后您可以将其转换为字符串。然后,您可以通过将字符串拆分为空格来解析字符串。然后迭代生成的字符串数组。
如果您没有理由使用实际的完整字符串,则可以使用List对象,并在代码中的相同位置对其使用add。在这种情况下,你不需要空间。然后,您就可以简单地遍历列表。
您仍然可以通过打印列表中的元素来打印输出。
https://stackoverflow.com/questions/26287034
复制相似问题