晚上好,

我正在尝试完成一个涉及JFrame的简单学校GUI项目,但是我被困在正确返回除数的问题上,然后将它们与feedback.setText()部分一起显示。指令如下:

编写一个Java代码,该代码创建一个GUI来接受来自用户的整数作为输入,并创建输入值的所有除数。您的框架应包含以下组件:

JLabel:输入一个整数以查找所有除数

JTextField:从用户读取输入

JButton:启动过程

JLabel:显示输出

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;



    public class DivisorException extends JFrame implements ActionListener{

//data fields
final int WIDTH = 300;
final int HEIGHT = 200;
public String divisors;
private int num;
private JButton find = new JButton("Find");
private JLabel question =  new JLabel("Enter a number to find all of its divisors");
private JTextField answer = new JTextField(8);
private JLabel feedback = new JLabel("");


//constructor
public DivisorException(){

    //call super class constructor  --> "Name the Window"
    super("Divisor");

    //set characteristics
    setSize(WIDTH,HEIGHT);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout());

    //add components
    add(question);
    add(answer);
    answer.addActionListener(this);
    add(find);
    find.addActionListener(this);
    add(feedback);
    }


 @Override
 public void actionPerformed(ActionEvent e){
        try{
            num = Integer.parseInt(answer.getText());
                if(e.getSource().equals(find)){
                feedback.setText("The divisors are: " + divisors);

                }


            }catch(NumberFormatException ex){
                feedback.setText("Invalid input. Enter an integer!");
                answer.setText("");
                }
        }


    private String divisor(int num){

        String divisors = "";
        for(int i = 1; i <= num; i++){
            if(num % i == 0){

                divisors = (i + ", ");
            }
        }
        return divisors;
    }

}

最佳答案

你有几个问题


您不是在调用divisor,也不是将值分配给任何内容,因此divisors始终是null
您正在隐藏divisors中的divisor实例字段,因此分配给它的任何内容都不会反映在其他地方
您没有将循环的结果附加到divisors,所以您只会得到最后一个值


首先,我将略微更改divisor以说明我的意思...

private String divisor(int num) {

    StringJoiner sj = new StringJoiner(", ");
    for (int i = 1; i <= num; i++) {
        if (num % i == 0) {
            sj.add(Integer.toString(i));
        }
    }
    return sj.toString();
}


首先,我删除了divisors的声明并将其替换为StringJoiner,它更简单并且给出了更好的结果,但是突出了阴影问题。

接下来,我更新了actionPerformed方法以实际调用divisor方法并将结果分配给divisors

@Override
public void actionPerformed(ActionEvent e) {
    try {
        num = Integer.parseInt(answer.getText());
        if (e.getSource().equals(find)) {
            divisors = divisor(num);
            feedback.setText("The divisors are: " + divisors);

        }

    } catch (NumberFormatException ex) {
        feedback.setText("Invalid input. Enter an integer!");
        answer.setText("");
    }
}

10-08 07:12