多项式 GUI 不起作用



我必须制作一个对多项式执行运算的GUI,但我不断收到我无法摆脱的NullPointerExceptions。在输出上,它不显示任何内容。我试图调试我的程序,据我所知,我从键盘插入的多项式不知何故没有被处理到系统中,即使它们不应该被处理,也被认为是空的。如何使我的程序正常工作?我需要尽快得到答案。

如果你向下滚动,你会发现我得到的异常,但这取决于我执行的操作。例如,加法不返回异常,而是返回 0。

以下是所有 4 个类,适合任何想要将它们放入编译器并测试它们的人:

类多项式

public class Polynomial {
    private int[] coef;
    private int degree;
    public boolean polyError = false;
    public Polynomial(int deg, int[] c)
    {
        degree = deg;
        coef = new int [deg +  1];
        for(int i = 0; i <= deg; i++)
        {
            coef[i] = c[i];
        }
    }
    public Polynomial() {
    }
    public Polynomial stringToPolynomial( String input)
    {   try {
            if(input.indexOf('x')>=0)
            {
                // first you need to configurate the string
                // write 1 for the powers where the coeff is 1
                input = input.replace("+x","+1x"); // positive
                input = input.replace("-x","-1x"); // negative
                // replace all - with +-
                input= input.replace("-","+-");
                // replace x with x^1
                input = input.replace("x+","x^1+"); // positive
                input = input.replace("x+-","x^1+-"); // negative
                // if the last element of the string is x then add ^1
                if(input.charAt(input.length()-1)=='x') input = input+"^1";
                //if the first element of the string is x add 1 before it
                if(input.charAt(0) == 'x') input = "1"+input;
                if(input.charAt(0) == '+') input = input.substring(1);
                // seconf you split the string and get the powers and coef
                // split the string
                String[] parts = input.split("\+");
                //get the degree
                String[] dg = parts[0].split("x\^");
                int degree = Integer.parseInt(dg[1]);
                int[] coeff = new int[degree+1];
                for (String part : parts)
                {
                    //delete all ^ characters
                    part=part.replace("^","");
                    //split the string c
                    String[] c= part.split("x");
                    try
                    {
                        coeff[Integer.parseInt(c[1])] = Integer.parseInt(c[0]);
                    }
                    catch(ArrayIndexOutOfBoundsException e)
                    {
                        coeff[0] = Integer.parseInt(c[0]);
                    }
                }
                return new Polynomial(degree,coeff);
            }
            else{
                int degree = 0;
                int[] coeff = new int[degree+1];
                coeff[0] = Integer.parseInt(input);
                return new Polynomial(degree,coeff);
            }
    }
    catch(NumberFormatException e)
    {
        polyError = true;
        return new Polynomial();
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
        polyError = true;
        return new Polynomial();
    }
}
    // Extract from the string inserted by the user the coef and the degree of the polynomials
   /* public Polynomial (String input) {
        // Bring the input polynomial string to a convenient form:
        input = input.replaceAll("\*","");
        input = input.replaceAll("-","+-");
// Split polynomial into "raw" coef (ceofficient + degree)
       String[] inputCoef = input.split("\+");
// Split each "raw" coefficient and determine the coefficient
        for (String s: inputCoef) {
            int power = 0;
            if (s.length() > 0)
            {
                if (s.endsWith("x")) {
                    power = 1;
                }
                String[] temp = s.split("x");
                if (temp.length > 1)
                {
                    if (temp[1].indexOf('^') != -1) {
                        temp[1] = temp[1].replaceAll("\^", "");
                    }
                    power = Integer.parseInt(temp[1]);
                    if (temp[0].length() == 0) {
                        this.coef[power] += 1;
                    } else {
                        this.coef[power] += Integer.parseInt(temp[0]);
                    }
                }
                else if (s.equals("x"))
                {
                    this.coef[1] += 1;
                }
                else if (temp[0].equals("-"))
                {
                    this.coef[power] -= 1;
                }
                else
                {
                    this.coef[power] += Integer.parseInt(temp[0]);
                }
            }
            this.degree = (power > this.degree ? power : this.degree);
        }*/

    // Write the string format of the polynomial at the output
    public String toString() {
        if (this.degree == 0)
            return " " + coef[0];
        if (this.degree == 1)
            return coef[1] + " x+ " + coef[0];
        String s = coef[this.degree] + " x^ " + this.degree;
        for (int i = this.degree - 1; i >= 0; i--) {
            if (coef[i] == 0)
                    continue;
            else if (coef[i] > 0)
                    s = s + " + " + (coef[i]);
            else if (coef[i] < 0)
                    s = s + " - " + (-coef[i]);
            if (i == 1)
                    s = s + "x";
            else if (i > 1)
                    s = s + " x^ " + i;
        }
        return s;
    }
    // Method that returns the degree of a polynomial
    public int getDegree() {
        int deg = 0;
        for (int i = 0; i < coef.length; i++)
            if (this.coef[i] != 0)
                deg = i;
        return deg;
    }
    // Addition
    public Polynomial add (Polynomial p) {
        int maxDegree = this.degree > p.degree ? this.degree : p.degree;
        int[] sumCoef = new int[maxDegree + 1];
        for (int i = 0; i < this.degree; i++)
            sumCoef[i] += this.coef[i];
        for (int i = (this.degree + 1); i < p.degree; i++)
            sumCoef[i] = p.coef[i];
        return new Polynomial(maxDegree, sumCoef);
        }
    // Differentiation
        public void differentiate()
        {
            this.coef[0] = 0;
            for (int i = 1; i <= this.degree; i++) {
                if (this.coef[i] != 0)
                {
                    this.coef[(i - 1)] = (this.coef[i] * i);
                    this.coef[i] = 0;
                }
            }
            this.degree = (this.degree > 0 ? this.degree - 1 : 0);
        }
    public boolean isEqual (Polynomial p) {
        if (this.degree != p.degree) return false;
        for (int i = this.degree; i >= 0; i--)
            if (this.coef[i] != p.coef[i]) return false;
        return true;
    }
    // Multiplication
    public Polynomial multiply (Polynomial p) {
        int[] mulCoef = new int[this.degree + p.degree + 1];
        int mulDegree = 0;
        for (int i = this.degree; i >= 0; i--) {
            for (int j = p.degree; j >= 0; j--) {
                if ((this.coef[i] != 0) && (p.coef[j] != 0))
                {
                    mulCoef[(i + j)] += this.coef[i] * p.coef[j];
                    mulDegree = i + j > mulDegree ? i + j : mulDegree;
                }
            }
        }
        this.degree = mulDegree;
        this.coef = mulCoef;
        return new Polynomial(mulDegree, mulCoef);
    }
    // Subtraction
    public void subtract(Polynomial p)
    {
        int subDegree = 0;
        int maxGrade = this.degree > p.degree ? this.degree : p.degree;
        this.degree = maxGrade;
        for (int i = maxGrade; i >= 0; i--) {
            this.coef[i] -= p.coef[i];
        }
        if (this.coef[maxGrade] == 0)
        {
            for (int j = maxGrade - 1; j >= 0; j--) {
                subDegree = this.coef[j] > 0 ? j : subDegree;
            }
            this.degree = subDegree;
        }
        else
        {
            this.degree = maxGrade;
        }
    }
    // Calculate value at a given point x
    public int calculateValue (int x) {
        int val = 0;
        for (int i = this.degree; i >= 0; i--)
            val += this.coef[i] * Math.pow(x, i);
        return val;
    }
}

类视图

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class View extends JFrame {
    private JTextField insertP1 = new JTextField(50);
    private JTextField insertP2 = new JTextField(50);
    private JTextField showResult = new JTextField(50);
    private JButton addBtn = new JButton("Add");
    private JButton subBtn = new JButton("Subtract");
    private JButton mulBtn = new JButton("Multiply");
    private JButton diffBtn = new JButton("Differentiate");
    private JButton calcBtn = new JButton("Calculate value");
    private JButton eqBtn = new JButton("Check for equality");
    private JButton clearBtn = new JButton("Clear");
    public View() {
        // Layout the components.
        JPanel polynomial1 = new JPanel();
        polynomial1.setLayout(new FlowLayout());
        polynomial1.add(new JLabel("Polynomial 1: "));
        polynomial1.add(insertP1);
        JPanel polynomial2 = new JPanel();
        polynomial2.setLayout(new FlowLayout());
        polynomial2.add(new JLabel("Polynomial 2: "));
        polynomial2.add(insertP2);
        JPanel operations = new JPanel();
        operations.setLayout(new FlowLayout());
        operations.add(addBtn);
        operations.add(subBtn);
        operations.add(mulBtn);
        operations.add(diffBtn);
        operations.add(calcBtn);
        operations.add(eqBtn);
        operations.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        JPanel result = new JPanel();
        result.setLayout(new FlowLayout());
        result.add(new JLabel("Result: "));
        result.add(showResult);
        result.add(clearBtn);
        // Finalize layout
        JPanel panel1 = new JPanel(); // panel where the user inserts the value of the first polynomial
        panel1.setLayout(new FlowLayout());
        panel1.add(polynomial1);
        JPanel panel2 = new JPanel(); // panel where the user insert the value of the second polynomial
        panel2.setLayout(new FlowLayout());
        panel2.add(polynomial2);
        JPanel panel3 = new JPanel(); // panel where the operations to be selected are placed
        panel3.setLayout(new FlowLayout());
        panel3.add(operations);
        JPanel panel4 = new JPanel(); // panel where the result will be displayed
        panel4.setLayout(new FlowLayout());
        panel4.add(result);
        final JPanel finalPanel = new JPanel(); // the final panel
        finalPanel.setLayout(new BoxLayout(finalPanel, BoxLayout.Y_AXIS));
        finalPanel.add(panel1);
        finalPanel.add(panel2);
        finalPanel.add(panel3);
        finalPanel.add(panel4);
        this.setContentPane(finalPanel);
        this.pack();
        this.setResizable(false);
        this.setTitle("Polynomial Processing");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        showResult.setEditable(false);
    }
        public void clear() {
        insertP1.setText("");
        insertP2.setText("");
        showResult.setText("");
    }
    public void initialiseResult() {
        showResult.setText("");
    }
    public void displayResult(String result) {
        showResult.setText(result);
    }
    public String getP1() {
        return insertP1.getText();
    }
    public String getP2() {
        return insertP2.getText();
    }
    public void addClearListener(ActionListener clear) {
        clearBtn.addActionListener(clear);
    }
    public void addAddListener(ActionListener add)
    {
        addBtn.addActionListener(add);
    }
    public void addSubListener(ActionListener sub) {
        subBtn.addActionListener(sub);
    }
    public void addEqListener(ActionListener eq) {
        eqBtn.addActionListener(eq);
    }
    public void addMultListener(ActionListener mul) {
        mulBtn.addActionListener(mul);
    }
    public void addDiffListener(ActionListener diff) {
        diffBtn.addActionListener(diff);
    }
    public void addCalcListener(ActionListener calc) {
        calcBtn.addActionListener(calc);
    }
}

类控制器

import java.awt.event.*;
import javax.swing.*;
public class Controller {
    private Polynomial pol1 = new Polynomial();
    private Polynomial pol2 = new Polynomial();
    private View view;
    public Controller(View view) {
        this.view = view;
        view.addAddListener(new AddListener());
        view.addSubListener(new SubListener());
        view.addClearListener(new ClearListener());
        view.addEqListener(new EqualListener());
        view.addMultListener(new MulListener());
        view.addDiffListener(new DiffListener());
        view.addCalcListener(new CalcListener());
    }
    class AddListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String p1 = view.getP1();
            String p2 = view.getP2();
            view.initialiseResult();
            pol1.stringToPolynomial(p1);
            pol2.stringToPolynomial(p2);
            view.displayResult((pol1.add(pol2)).toString());
        }
    }
    class SubListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String p1 = view.getP1();
            String p2 = view.getP2();
            view.initialiseResult();
            pol1.stringToPolynomial(p1);
            pol2.stringToPolynomial(p2);
           // view.displayResult((pol1.subtract(pol2));
        }
    }
    class ClearListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            view.clear();
        }
    }
    class EqualListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String p1 = view.getP1();
            String p2 = view.getP2();
            view.initialiseResult();
            pol1.stringToPolynomial(p1);
            pol2.stringToPolynomial(p2);
            if (pol1.isEqual(pol2)) {
                view.displayResult("true");
            } else view.displayResult("false");
            //  view.displayResult((pol1.isEqual(pol2)));
        }
    }
    class MulListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String p1 = view.getP1();
            String p2 = view.getP2();
            view.initialiseResult();
            pol1.stringToPolynomial(p1);
            pol2.stringToPolynomial(p2);
            view.displayResult((pol1.multiply(pol2)).toString());
        }
    }
    class DiffListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            Object[] options = {"p1'", "p2'"};
            int choice = JOptionPane.showOptionDialog(view,
                    "Which polynomial do you want to differentiate?",
                    "Choose an option",
                    0,
                    3,
                    null,
                    options,
                    options[0]);
            if (choice == 0) { // if the user chose p1'
                String p1 = view.getP1();
                pol1.stringToPolynomial(p1);
                pol1.differentiate();
                view.displayResult(pol1.toString());
            } else if (choice == 1) { // if the user chose p2'
                String p2 = view.getP2();
                pol2.stringToPolynomial(p2);
                pol2.differentiate();
                view.displayResult(pol2.toString());
            }
        }
    }
    public class CalcListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            Object[] options = {"p1(x)", "p2(x)"};
            JPanel panel = new JPanel();
            panel.add(new JLabel("Enter a value for x and choose an operation"));
            JTextField textField = new JTextField(5);
            panel.add(textField);
            int choice = JOptionPane.showOptionDialog(view, panel, "Calculate value",
                    0, -1,
                    null, options, null);
            String input = textField.getText();
            boolean isInteger = true;
            if (input == null) {
                isInteger = false;
            } else {
                int length = input.length();
                if (length == 0) {
                    isInteger = false;
                } else {
                    int i = 0;
                    if (input.charAt(0) == '-') {
                        if (length == 1) {
                            isInteger = false;
                        }
                    }
                    for (i = 1; i < length; i++) {
                        char c = input.charAt(i);
                        if ((c <= '/') || (c >= ':')) {
                            isInteger = false;
                        }
                    }
                }
            }
            if (isInteger) {
                int x = Integer.parseInt(input);
                if (choice == 0) {
                    String p1 = view.getP1();
                    pol1.stringToPolynomial(p1);
                    int value = pol1.calculateValue(x);
                    System.out.println(value);
                } else if (choice == 1) {
                    String p2 = view.getP2();
                    pol2.stringToPolynomial(p2);
                    int value = pol2.calculateValue(x);
                    System.out.println(value);
                } else {
                    view.displayResult("The value you entered is not a number!");
                }
                String result = new String(view.toString());
                view.displayResult(result.toString());
            }
        }
    }
}

类 MVC

public class MVC {
    public static void main(String[] args) {
        View view = new View();
        Controller controller = new Controller(view);
        view.setVisible(true);
    }
}

异常示例

  Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Polynomial.multiply(Polynomial.java:200)
        at Controller$MulListener.actionPerformed(Controller.java:69)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
        at java.awt.Component.processMouseEvent(Component.java:6525)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
        at java.awt.Component.processEvent(Component.java:6290)
        at java.awt.Container.processEvent(Container.java:2234)
        at java.awt.Component.dispatchEventImpl(Component.java:4881)
        at java.awt.Container.dispatchEventImpl(Container.java:2292)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
        at java.awt.Container.dispatchEventImpl(Container.java:2278)
        at java.awt.Window.dispatchEventImpl(Window.java:2750)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)
        at java.awt.EventQueue.access$500(EventQueue.java:97)
        at java.awt.EventQueue$3.run(EventQueue.java:702)
        at java.awt.EventQueue$3.run(EventQueue.java:696)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.awt.EventQueue$4.run(EventQueue.java:724)
        at java.awt.EventQueue$4.run(EventQueue.java:722)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

我在Controller.MulListener中看到一个错误。当您致电时

pol1.stringToPolynomial(p1); 

您正在返回一个值。但是,您不会将值存储在任何地方。如果将该值存储到 pol1,它将修复错误。

pol1 = pol1.stringToPolynomial(p1); 

更一般地说,如果要保留 stringToPolynomial(String) 作为类方法,则应让它将值设置为调用它的实例。 否则,将其编码为静态方法,并将其视为接受字符串并返回多项式实例的工厂方法,按如下方式调用它:

pol1 = Polynomial.stringToPolynomial(p1); 

最新更新