一个正整数有可能可以表示为n(n>=2)个连续正整数之和,如:
15=1+2+3+4+5
15=4+5+6
15=7+8
编程设计一个小界面,能输入一个数,输出它用整数表示的每项,如上所示。最好有清除功能,带点注释就更好了!!!
------解决方案--------------------
JDK8运行通过,没装JDK8的,你把()->这种Lambda改一下就好了
import java.awt.*;
import javax.swing.*;
public class CompsDemo {
private final JFrame frame;
private final JTextField textField;
private final JButton runBtn;
private final JTextArea textArea;
public CompsDemo() {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
runBtn = new JButton("Run");
runBtn.addActionListener((e) -> runBtnOnClick());
textField = new JTextField(20);
JLabel label = new JLabel("Enter a number");
JPanel p = new JPanel();
p.add(label);
p.add(textField);
p.add(runBtn);
frame.add(p, BorderLayout.NORTH);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane sp = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.add(sp, BorderLayout.CENTER);
frame.setMinimumSize(new Dimension(500, 400));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void runBtnOnClick() {
int n = Integer.parseInt(textField.getText());
String result = getCompsOf(n);
SwingUtilities.invokeLater(() -> textArea.setText(result));
}
private static String getCompsOf(int n) {
StringBuilder comps = new StringBuilder();
int max = (int) ((Math.sqrt(n * 8 + 1) - 1) / 2);
for (int i = 2; i <= max; i++) {
if ((i & 1) == 0) {
// i is even
int x = i / 2;
if (n % x != 0) {
continue;
}
int y = n / x;
if ((y & 1) == 0) {
// y is even
continue;
}
// y is odd
int z = y / 2 - x + 1;
comps.append(n + "=" + z);
for (int j = 1; j < i; j++) {
comps.append("+" + (z + j));
}
comps.append(System.lineSeparator());
} else {
// i is odd
if (n % i != 0) {
continue;
}
int x = n / i - i / 2;
comps.append(n + "=" + x);
for (int j = 1; j < i; j++) {
comps.append("+" + (x + j));
}
comps.append(System.lineSeparator());
}
}
return comps.toString();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CompsDemo());
}
}