【求助】程煦媛都是写得了代码,查得出异常,上得了厅堂下得了厨房,---------------(一个Java计算器)查个异常让我们这些沙弥见识见识

lqvc2011 2013-08-16 03:58:15
package calculator02;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class Calc
{
// 框架
private JFrame jf = new JFrame("calc");
private JPanel jptext = new JPanel();
private JPanel keyboarder = new JPanel();
private GridBagLayout gb = new GridBagLayout();
private GridBagConstraints gbc = new GridBagConstraints();
// 辅助

private static boolean sign = false;
private static String info = "";
private static String bufferKey;
private static String copy;
private static String bs; // bufferScreen;
private static String expression = "";
private static String bsv = "Ans="; // bufferScreenView;
private static String temp = "";
private static String[] index = new String[50];
private static JTextField screen = new JTextField(20);
private static JTextField screenView = new JTextField(20);

private static String[] key = "c < / x 7 8 9 - 4 5 6 + 1 2 3 = 0 ."
.split(" ");
private static JButton button[] = new JButton[key.length];

// 逆波兰式
private Stack<Double> operandStack = new Stack<Double>();// 操作数堆栈
private Stack<String> operatorStack = new Stack<String>();// 操作符堆栈
//private String expressionPolish;// 算数表达式
private double resultPolish = 0.0;// 计算结果
private Map<String, Integer> priorityMap = new HashMap<String, Integer>();// 用于存储操作符优先级的Map

// 逆波兰式代码
public Calc()
{
priorityMap.put("+", 0);
priorityMap.put("-", 0);
priorityMap.put("*", 1);
priorityMap.put("/", 1);
}

public int getPriority(String op)// 得到一个操作符的优先级
{
return priorityMap.get(op);//////////异常1
}

public boolean highPriority(String op)// 判断操作符的优先级在堆栈里面是否最为高
{
int opPri = getPriority(op);// 当前操作符的优先级//////////异常2
if (!operatorStack.empty())
{
for (String s : operatorStack)// 把opriority 里的字符一个一个取出来存在s里
{
int priority = getPriority(s);
if (opPri < priority)
return false;

}
}
return true;
}

// 把表达式转化成逆波兰式
public String expToIpn(String expressionPolish)
{
int index = 0;
int end = 0;
String IpnPolish = "";// 这是个什么东东
// Ipn保存着数字字符串,重点在它保存的顺序是先数字再字符串
for (int i = 0; i < expressionPolish.length(); i++)
{
String temps = String.valueOf(expressionPolish.charAt(i));
if (temps.matches("[0-9.]"))// 检查是否是数字
{
end++;
} else
{
String tempOperand = expressionPolish.substring(index, end);// 得到操作数,同时也是从一个字符串里取出数字
IpnPolish += tempOperand + ",";
String tempOperator = expressionPolish.substring(end, ++end);// 得到操作符
if (tempOperator.equals("!"))// 假如到表达式的最后将操作符 全部弹出
{
while (!operatorStack.empty())
{
IpnPolish += operatorStack.pop() + ",";
}
} else
{
if (highPriority(tempOperator))// 优先级高的压入操作符堆栈//////////异常3
{
operatorStack.push(tempOperator);
} else
{
while (!operatorStack.empty())//
{
IpnPolish += operatorStack.pop() + ",";// pop
// 移除堆栈顶部的对象,并作为此函数的值返回该对象。这里在for循环中,会把pop里的元素全部输出
}
operatorStack.push(tempOperator);
}

index = end;
}
System.out.println("拆数" + tempOperand + "," + tempOperator);
//
}

}
return IpnPolish;

}

public double calculateIpn(String[] IpnPolish)// 计算逆波兰式
{
for (int i = 0; i < IpnPolish.length; i++)
{
// System.out.println(IpnPolish[i]);
if (IpnPolish[i].matches("^[0-9]+.?[0-9]*$"))// 正则表达式判断是数字
{
operandStack.push(Double.parseDouble(IpnPolish[i]));// 如果是数字就压栈
System.out.println(IpnPolish[i]);
} else
{

popOperand(IpnPolish[i]);
System.out.println(IpnPolish[i]);
}
}
return resultPolish;
}

// 遇到操作符时,弹出操作数,进行相应操作,并保村result
public void popOperand(String operator)
{
double d1 = operandStack.pop();
double d2 = operandStack.pop();
// System.out.println(d1 + operator + d2);
if (operator.equals("+"))
resultPolish = d2 + d1;
if (operator.equals("-"))
resultPolish = d2 - d1;
if (operator.equals("*"))
resultPolish = d2 * d1;
if (operator.equals("/"))
resultPolish = d2 / d1;
// System.out.println(resultPolish );
operandStack.push(resultPolish);
}

public void clear(String str)
{
str = "0";
}


public void init()
{

keyMonitor Kmonitor = new keyMonitor();
keyboarder.setLayout(gb);
gbc.fill = GridBagConstraints.NONE;
for (int i = 0; i < key.length; i++)
{
button[i] = new JButton(key[i]);
button[i].addActionListener(Kmonitor);
}
gbc.gridwidth = 1;
addButton(button[0]);
addButton(button[1]);
gbc.ipadx = 14;
gb.setConstraints(button[2], gbc);
keyboarder.add(button[2]);
gbc.gridwidth = GridBagConstraints.REMAINDER;
addButton(button[3]);
gbc.gridwidth = 1;
addButton(button[4]);
addButton(button[5]);
addButton(button[6]);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.ipadx = 13;
gb.setConstraints(button[7], gbc);
keyboarder.add(button[7]);

gbc.gridwidth = 1;
addButton(button[8]);
addButton(button[9]);
addButton(button[10]);
gbc.gridwidth = GridBagConstraints.REMAINDER;
addButton(button[11]);
gbc.gridwidth = 1;
addButton(button[12]);
addButton(button[13]);
addButton(button[14]);

gbc.gridx = 0;// 按钮的X坐标,
gbc.gridy = 4;// 按钮的Y坐标
gbc.ipadx = 61;// 按钮的X方向长度,如果Y方向没有设置默认与前一个相同
gbc.gridwidth = 2;// 按钮跨两格
gb.setConstraints(button[16], gbc);// 自己重写方法
keyboarder.add(button[16]);

gbc.gridx = 2;
gbc.gridy = 4;
gbc.ipadx = 14;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gb.setConstraints(button[17], gbc);
keyboarder.add(button[17]);

gbc.gridx = 3;
gbc.gridy = 3;
gbc.ipadx = 10;
gbc.ipady = 42;
gbc.gridheight = 2;
gb.setConstraints(button[15], gbc);
keyboarder.add(button[15]);

// 设置screen的属性 sc
screen.setText("0");
screenView.setText("Ans=");
secreenMethod(screen);
secreenMethod(screenView);
// 将组件添加到Jpanel中再添加到Jframe中
jptext.setLayout(new BoxLayout(jptext, BoxLayout.Y_AXIS));
jptext.add(screenView);
jptext.add(screen);
// GridBagLayout里有没有设置行间距的方法??????????????????
jf.add(jptext, BorderLayout.NORTH);
jf.add(keyboarder);
jf.setResizable(false);
jf.setSize(220, 260);
jf.setLocation(900, 100);
myEvent();
jf.setVisible(true);
}

public void myEvent()
{
jf.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}

public void secreenMethod(JTextField jt)
{
jt.setHorizontalAlignment(JTextField.RIGHT);
jt.setEnabled(false);
}

public void addButton(JButton button)
{
gbc.ipadx = 10;
gbc.ipady = 7;
gb.setConstraints(button, gbc);
keyboarder.add(button);
}

public class keyMonitor implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// String info = "";
// String bsv = "";
Object o = e.getSource();// o = getkey
for (int i = 0; i < key.length; i++)
{
if (o == button[i] && i != 0 && i != 1 && i != 15)// 此处可优化,
{
String tempInfo = button[i].getText().toString();
for (int j = 0; j < tempInfo.length(); j++)
{// 去除按键后自带的空格
if (tempInfo.charAt(j) != ' '
&& tempInfo.charAt(j) != '=')
{
info = info + tempInfo.charAt(j);
}
}

}
}
// 静态变量和局部变量的区别可以通过info编程局部变量来观察
// if(info)
if (o == button[1])
{
if (info == "")
{

} else
info = info.substring(0, info.length() - 1);///////异常
System.out.println(info + "--------" + info.length());
}
screen.setText(info);

if (o == button[0])
{
info = "";
screen.setText("0");
screenView.setText("Ans=");
}


if (o == button[15])
{
if (info == "")
{
} else
{
if (info.charAt(0) == '/' || info.charAt(0) == '+'
|| info.charAt(0) == '-' || info.charAt(0) == 'x'
|| info.charAt(0) == '.'
|| info.charAt(info.length() - 1) == '.'
|| info.charAt(info.length() - 1) == '+'
|| info.charAt(info.length() - 1) == '-'
|| info.charAt(info.length() - 1) == 'x'
|| info.charAt(info.length() - 1) == '/')// 此处可以用正则表达式优化
{
sign = true;
//
System.out.println("the line sliped!!");
System.out.println(info.length());
}

// 排除两个连续的运算符
for (int i = 0; i < info.length(); i++)
{
if (sign != true)
{
if (info.charAt(i) == '/' || info.charAt(i) == '+'
|| info.charAt(i) == '-'
|| info.charAt(i) == 'x'
|| info.charAt(i) == '.')
{
if (info.charAt(i + 1) == '+'
|| info.charAt(i + 1) == '-'
|| info.charAt(i + 1) == 'x'
|| info.charAt(i + 1) == '/'
|| info.charAt(i + 1) == '.')
{
sign = true;
}

}
}
}

}
if (sign == true)
{
screenView.setText("Ans");
screen.setText("ERROR");
info = "";
sign = false;
} else
{
// sign = true;
if (info == "")
{screenView.setText("Ans=");
screen.setText("0");}
else
{screenView.setText(info.concat("="));



String Transform = Adddot(info);


String result = getResult(Transform);//////////异常5
System.out.println(result);
screen.setText(result);
info = "";
}
}
}
// 好了开始做backspace现在的功能就类似于手机的计算机,还有一些小bug还有一些小bug,比如输入一个数字后一直按<就会报错,BUg
}
}
//(接下)
...全文
226 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
流星陨落 2013-08-18
  • 打赏
  • 举报
回复
lqvc2011 2013-08-17
  • 打赏
  • 举报
回复
计算器做完了,我的神啊,
发个图大家欣赏一下。
lqvc2011 2013-08-17
  • 打赏
  • 举报
回复
引用 12 楼 u011562317 的回复:
[quote=引用 10 楼 lqvc2011 的回复:] [quote=引用 9 楼 u011562317 的回复:] 学习了,接分可以有么?
什么叫接分[/quote] 你发问题的时候不是给了悬赏分么,40分,结贴的时候这些分可以分发给你想给的哪一楼,也可以分配到回帖的多层楼里的多个人,以表示感谢。另外也可以追加分,如果你想特别感谢某人的话。[/quote] 长姿势了
dwwhu 2013-08-17
  • 打赏
  • 举报
回复
引用 10 楼 lqvc2011 的回复:
[quote=引用 9 楼 u011562317 的回复:] 学习了,接分可以有么?
什么叫接分[/quote] 你发问题的时候不是给了悬赏分么,40分,结贴的时候这些分可以分发给你想给的哪一楼,也可以分配到回帖的多层楼里的多个人,以表示感谢。另外也可以追加分,如果你想特别感谢某人的话。
valenon 2013-08-17
  • 打赏
  • 举报
回复
学习了,接分
lqvc2011 2013-08-17
  • 打赏
  • 举报
回复
引用 9 楼 u011562317 的回复:
学习了,接分可以有么?
什么叫接分
dwwhu 2013-08-17
  • 打赏
  • 举报
回复
学习了,接分可以有么?
TifaTII 2013-08-17
  • 打赏
  • 举报
回复
hahah
lqvc2011 2013-08-16
  • 打赏
  • 举报
回复
我为大家公答案了,是写的那个Adddot出错了,我忘了在逆波兰式里有一个加dot的方法,在家了一个就错了,然后还有就是NullPointerException是在public String getResult(String str) { if (!str.equals("0")) { String temp = ""; String[] IpnPolish = expToIpn(str).split(",");//////////异常4 temp = temp + calculateIpn(IpnPolish);// 最终结果 return temp; } return "0"; } 和String result = getResult(info.concat("="));/////////只要改了就好了
lqvc2011 2013-08-16
  • 打赏
  • 举报
回复
我知道了一点,大家等一下,我马上就去改
xsbawxj432 2013-08-16
  • 打赏
  • 举报
回复
这几个地方看看哪有问题 at calculator02.Calc.getPriority(Calc.java:59) at calculator02.Calc.highPriority(Calc.java:64) at calculator02.Calc.expToIpn(Calc.java:104) at calculator02.Calc.getResult(Calc.java:402)
xsbawxj432 2013-08-16
  • 打赏
  • 举报
回复
这是个计算器?空指针异常?哪里空了~用debug看看
lqvc2011 2013-08-16
  • 打赏
  • 举报
回复
我要不要暂时放弃这个课程设计呢
lqvc2011 2013-08-16
  • 打赏
  • 举报
回复
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at calculator02.Calc.getPriority(Calc.java:59) at calculator02.Calc.highPriority(Calc.java:64) at calculator02.Calc.expToIpn(Calc.java:104) at calculator02.Calc.getResult(Calc.java:402) at calculator02.Calc$keyMonitor.actionPerformed(Calc.java:385) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) 初学,就是这一大堆,还有我把有问题的那几行都标记了源码里面有
失落夏天 2013-08-16
  • 打赏
  • 举报
回复
你还是发报的异常和异常代码行吧。。
lqvc2011 2013-08-16
  • 打赏
  • 举报
回复
//(接上) // 作为桥梁的两个方法 public String getResult(String str) { if (str != "0") { String temp = ""; String[] Ipn = expToIpn(str).split(",");//////////异常4 // String[] IpnPolish = str.split(","); temp = temp + calculateIpn(Ipn);// 最终结果 return temp; } return "0"; } // 再写一个给字符添加,的方法 public String Adddot(String str) { if (str != "") { String temp = ""; for (int i = 0; i < str.length() - 1; i++) temp = temp + str.charAt(i) + ","; return temp; } return "0"; } public static void main(String[] args) { new Calc().init(); } } //

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧