只是为了说明这一点,它是学校,所以我不寻找直接的答案只是有用的建议。我仅限于我可以使用的内置方法。基本上我要将一个多项式转换为数组p。然后再换成p1。最后将这些加在一起。出于某种原因,我得到错误“数组需要,但多项式找到”,我不知道为什么。老师也设置了返回双重价值,但我不确定为什么。忽略乘法部分。其他一切按预期工作。任何提示将不胜感激。多项式阵列不工作
import java.util.Scanner;
class Polynomial {
final int MAXSIZE = 20;
int p[]; //coefficient
int n; //degree
//array constructor
Polynomial() {
p = new int [MAXSIZE];
n = -1;
}
void readP() {
Scanner in = new Scanner(System.in);
System.out.print("Enter degree: ");
n = in.nextInt();
for (int i = 0; i <= n; i++) {
System.out.print("Enter a p[" + i + "]:");
p[i] = in.nextInt();
}
System.out.println();
}
void printP() {
if (p[0] < 0)
System.out.printf("-");
for (int i = 0; i < n; i++)
if (p[i] != 0) {
if (p[i] > 1)
System.out.printf(p[i] + "x^" + (n-i));
else if (p[i] == 1)
System.out.printf("x^" + (n-i));
if (p[i] < -1)
System.out.printf(p[i] * -1 + "x^" + (n-i));
else if (p[i] == -1)
System.out.printf("x^" + (n-i));
if (p[i+1] < 0)
System.out.printf(" - ");
else
System.out.printf(" + ");
}
if (p[n] > 0)
System.out.print(p[n]);
else
System.out.print(p[n] * -1);
System.out.println();
System.out.println();
}
double evalP(double x) {
int total = 0;
for (int i = n; i > 0; i--)
total += (p[i] * (Math.pow(x, i)));
total += p[n];
System.out.println();
return total;
}
double addP(Polynomial P1) {
for (int i = 0; i < n; i++)
p[i] = p[i] + P1[i];
return total;
}
double multiplyP(Polynomial P1) {
for (int i = 0; i < n; i++)
p[i] += p[i] * P1[i];
return p;
}
}
public class Lab5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Polynomial myPoly = new Polynomial();
String res;
Polynomial p1;
do {
System.out.println("1. Read Polynomial");
System.out.println("2. Print Polynomial");
System.out.println("3. Evaluate Polynomial");
System.out.println("4. Add Polynomial");
System.out.println("5. Multiply Polynomial");
System.out.println("Q. Quit");
System.out.print("Select: ");
res = in.next();
System.out.println();
switch (res.charAt(0)) {
case '1':
myPoly.readP();
break;
case '2':
myPoly.printP();
break;
case '3':
System.out.print("Enter x: ");
double x = in.nextDouble();
System.out.print(myPoly.evalP(x));
System.out.println();
System.out.println();
break;
case '4':
p1 = new Polynomial();
p1.readP();
myPoly.addP(p1);
break;
case '5':
p1 = new Polynomial();
p1.readP();
myPoly.multiplyP(p1);
System.out.println();
System.out.println();
break;
case 'Q': case 'q':
System.out.println("Bye!");
break;
default:
System.out.println("Invalid!");
System.out.println();
}
} while (res.charAt(0) != 'Q' && res.charAt(0) != 'q');
}
}
什么行给你这个错误? – slashms
您的Polynomial类不是数组,因此您不能在其实例上使用像'P1 [i]'这样的语法。我认为你的意思就像'P1.p [i]'? – azurefrog