由于无法弄清楚这个看似简单的代码,我感觉相当愚蠢,但作为初学者,我感到难过。我有一个带有textArea的GUI供用户输入数字,一个按钮应该“监听”这些数字,然后是一个textField来显示总和。我在textField中显示了数字,但我不确定如何总结它们。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
public class Main extends javax.swing.JFrame {
private JTextArea inputArea;
private JTextField resultField;
private JButton calcBtn;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Main inst = new Main();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public Main() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
inputArea = new JTextArea();
getContentPane().add(inputArea);
inputArea.setBounds(5, 12, 214, 233);
}
{
calcBtn = new JButton();
getContentPane().add(calcBtn);
calcBtn.setText("Obtain the sum");
calcBtn.setBounds(257, 113, 99, 23);
calcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
calcBtnActionPerformed(evt);
}
});
}
{
resultField = new JTextField();
getContentPane().add(resultField);
resultField.setBounds(242, 55, 139, 28);
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
private void calcBtnActionPerformed(ActionEvent evt) {
try {
String[] lines = inputArea.getText().split("<br/>");
int sum = 0;
for (int i = 0; i < lines.length; i++) {
resultField.setText(lines[i]);
}
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Enter numbers only");
}
}
}
答案 0 :(得分:0)
scanner.nextInt()
循环中致电while (scanner.hasNextInt())
。lines = text.split("\\s+");
,然后在添加之前将数组中的每个项解析为int。