功能性错误,请各位帮忙!
运行后,弹出的窗口 输入数字 会实现一个简单的加法运算,但总会把第一个加数丢失,请朋友们帮忙看看是什么原因!程序代码:
package 练习代码; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.InputMismatchException; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Example9_17 { public static void main(String args[]) { WindowInput win = new WindowInput(); win.setTitle("带输入对话框的窗口"); win.setBounds(80, 90, 280, 300); } } class WindowInput extends JFrame implements ActionListener { JTextArea showResult; JButton openInput; String regex = "[\\d\\s]+"; WindowInput() { openInput = new JButton("弹出输入对话框"); showResult = new JTextArea(); add(openInput, BorderLayout.NORTH); add(new JScrollPane(showResult), BorderLayout.CENTER); openInput.addActionListener(this); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String str = JOptionPane.showInputDialog(this, "输入数字,用空格隔开", "输入对话框", JOptionPane.PLAIN_MESSAGE); if(str != null) { Scanner scanner = new Scanner(str); double sum = 0; int k = 0; String i = scanner.next(); if(i.matches(regex)) { while(scanner.hasNext()) { try{ double number = scanner.nextDouble(); if(k == 0) showResult.append(""+number); else showResult.append("+"+number); sum += number; k++; } catch(InputMismatchException exp){ String t = scanner.next(); } } showResult.append("="+sum+"\n"); } else JOptionPane.showMessageDialog(this, "请输入数字好吗", "警告", JOptionPane.WARNING_MESSAGE); } } }