参考 https://blog.youkuaiyun.com/duoduo18up/article/details/82193122

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
Stack stack=new Stack();
int result=0;
for(int i=0;i<line.length();i++){
String temp=line.charAt(i)+"";
if(temp.matches("-")){
stack.push('-');
}
else if(temp.matches("\\d")){ //如果是数字
int count=0;
while(!stack.empty()){ //先弹出所有的符号
stack.pop();
count++;
}
for(int j=i+1;j<line.length();j++){ //查看后面是否还有数字
String other=line.charAt(j)+"";
if(other.matches("\\d")) {
temp=temp+other;
i=j;
}
else break;
}
int result_temp=Integer.valueOf(temp);
if(count%2!=0) result_temp=-result_temp;
result=result+result_temp;
}
}
System.out.println(result);
}
本文介绍了一个使用Java实现的简单计算器,它能从输入的字符串中解析并计算包含数字和负号的表达式。通过使用栈来跟踪负号的出现次数,确保了正确处理负数。此外,该程序能识别连续的数字字符并将其作为一个整体进行处理。
38

被折叠的 条评论
为什么被折叠?



