【发布时间】:2012-12-11 06:49:59
【问题描述】:
我正在为我的一门课程做作业,我将任何大小的“数字”作为格式正确的字符串。我使用三个堆栈,每个堆栈都将每个数字作为单独的数值。堆栈一将获取第一个值,堆栈二获取第二个值,堆栈三将结果值推入并弹出到字符串中。最后将字符串打印到屏幕上。
我的问题是我“随身携带”的能力 假设我在我的程序中添加了 7 和 15,我的程序将分别从堆栈 1 和 2 中弹出 7 和 5,将它们加在一起得到 12,这就是我的问题开始的地方,因为你们都看到那个还在堆栈,我需要一种方法来识别一个实际上是十位上的一个数字,依此类推,以获取更大的数字。
这是我的整个添加方法的帖子,它从我的 main 方法中接受命令行参数,但这并不是真正重要的,我试图尽可能彻底。
我希望我是彻底的,你们都理解我的问题,我很乐意更详细地阐述这个主题。
private static void addlargeNumbers(String x, String y)throws ParseException{
String o = x.replaceAll(",", "");
String t = y.replaceAll(",", "");
String r = "";
Stack<Integer> one = new Stack<Integer>();
Stack<Integer> two = new Stack<Integer>();
Stack<Integer> resstack = new Stack<Integer>();
int i = 0, j = 0;
while(i < o.length()){
one.push(Character.getNumericValue(o.charAt(i)));
i++;
}
while(j < t.length()){
two.push(Character.getNumericValue(t.charAt(j)));
j++;
}
while(!one.isEmpty() || !two.isEmpty()){
if(!one.isEmpty() && !two.isEmpty()){
resstack.push(one.pop() + two.pop());
}
else if(one.isEmpty()){
resstack.push(two.pop());
}
else{
resstack.push(one.pop());
}
}
while(!resstack.isEmpty()){
r += resstack.pop();
}
if(!x.isEmpty() && !y.isEmpty()){
System.out.printf("%s + %s = %s\n", x, y, r );
}
else if(x.isEmpty()){
System.out.printf("%s = %s\n", y, r);
}
else{
System.out.printf("%s = %s\n", x, r);
}
}
我的问题已得到解答,我已经得到它的工作,感谢您的帮助。
【问题讨论】:
标签: java regex string stack addition