在我的主类中,我有以下代码:
Polynomial P = new Polynomial(polynomial);
在另一个类中,我有以下代码:
public class Polynomial {
private int[] polynomial;
public Polynomial(int[] polynomial) {
this.polynomial = polynomial;
}
}
为什么构造函数 Polynomial(int[]) 未定义?
顺便说一句...主类中的多项式指向:
int [] polynomial = new int[count];
这是完整的主类:
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog(null, "This is the Polynomial Cal" +
"culator Menu. Please ente" +
"r your menu selection:\n (1) Enter c" +
"oefficients of polynomial P(x). \n (2) Enter co" +
"efficients of polynomial Q(x). \n (3) Sum polynomi" +
"als P(x) and Q(x). \n (4) Multiply polynomials P(x) and Q(" +
"x). \n (5) Quit.", "Polynomial Menu",JOptionPane.PLAIN_MESSAGE);
Scanner inputScanner =new Scanner(input); //Scanner for Menu
int userChoice = inputScanner.nextInt(); //Menu Choice
if(userChoice>=1 && userChoice<=5) //User Input Catch
{
switch(userChoice)
{
case 1: String coefficientInput= JOptionPane.showInputDialog(null, "Please enter th" +
"e coefficients of the terms in the polynom" +
"ial.(Ax^n, Bx^(n-1)...Yx,Z) \n Only ent" +
"er the values of the coeffien" +
"ts i.e (A + B - C + D) ");
Scanner countScanner = new Scanner(coefficientInput); //Scanner for count
int coefficient= countScanner.nextInt();
int count=1;
while(countScanner.hasNextInt())
{
count++;
countScanner.nextInt();
}
int [] polynomial = new int[count]; //Size of Array=Count
Scanner coefficientScanner = new Scanner(coefficientInput);
int term = 0;
System.out.println(count);
int i=0;
while(coefficientScanner.hasNextInt()) //Initialisation of array
{
term=coefficientScanner.nextInt();
polynomial[i]=term;
i++;
}
Polynomial P = new Polynomial(polynomial);
}
}
else
{
JOptionPane.showMessageDialog(null, "No option selected. Please try again.","Input Error",JOptionPane.ERROR_MESSAGE);
}
}
}
错误发生在 Polynomial P =new Polynomial(polynomial)
最佳答案
我猜测主类中名为polynomial
的引用并不指向int []
。如果它是Polynomial
类型的引用,您必须创建另一个采用Polynomial
的构造函数(又名“复制构造函数”),或者更改多项式的类型
.
我不喜欢你编写构造函数的方式。这样就不是私有(private)的了;您传入的引用是可变的。制作一份防御性副本。我的做法如下:
public class Polynomial {
private int[] coefficients;
public Polynomial(int[] coefficients) {
if (coefficients == null) throw new IllegalArgumentException("coefficients cannot be null");
this.coefficients = new int[coefficients.length];
System.arraycopy(0, coefficients, 0, this.coefficients, this.coefficients.length);
}
public Polynomial(Polynomial p) {
this(p.coefficients);
}
}
这也是一个幼稚的设计。没有浮点系数?如果您想对诸如 y = x^1000 + 1
之类的东西进行建模,那么效率很低。您将在一个非常大的数组中拥有两个非零系数。
更好的设计是创建一个单项式
并让一个多项式
维护它们的列表
。
关于java - 构造函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15361023/