gpt4 book ai didi

java - 通过构造函数从字符串输入中提取多项式变量

转载 作者:行者123 更新时间:2023-11-30 04:51:28 26 4
gpt4 key购买 nike

我希望有人能帮助我解决这个问题。我正在尝试添加一个构造函数,以允许从 3x^y 形式的字符串输入多项式数据,并将系数、变量和指数值放入类中定义的相应变量中。我实现的构造函数允许程序编译,但在运行应用程序时会卡住,如果...

这个:

trinomial[0] = new Term (3,'x',2);

设置为:

trinomial[0] = new Term ("3x^y");

基本上,我试图让定义的类接受两种形式的输入(字符串和 double /字符/指数格式)。任何有关此问题的帮助将不胜感激。

public class TrinomialTest {
static void printTrinomial(Term[] x) {
for (int i = 0; i < x.length; i++) {
//AUTOMATICALLY CALLS TOSTRING() WHEN PRINTLN
System.out.print(x[i]);
}
}

public static void main(String[] args) {
Term[] trinomial = new Term[3];
trinomial[0] = new Term(3, 'x', 2);
trinomial[1] = new Term(12, 'x', 1);
trinomial[2] = new Term(-23, 'x', 0);
printTrinomial(trinomial);
}
}

class Term {
private double coefficient; //the number
private char variable; // the letter
private int exponent;

public Term(double c, char v, int e) {
coefficient = c;
variable = v;
exponent = e;
}

//New Constructor
public Term(String Term) {
String c = "";
String v = "";
String e = "";
int exponentIndex = 0;
exponentIndex = Term.indexOf("^");

if (Term.substring(0, 1).matches("[0-9]")) {
c = Term.substring(0, 1);
v = Term.substring(1, 2);
} else {
c = "0";
v = Term.substring(0, 1);
}

do {
e = Term.substring(exponentIndex, exponentIndex + 1);
} while (Term.indexOf("^") != -1);

coefficient = Double.parseDouble(c);
variable = v.charAt(0);
exponent = Integer.parseInt(e);
}

public String toString() {
int c = (int) coefficient;

if (exponent == 1 && c > 0)
return ("" + "+" + c + variable);
else if (exponent == 1 && c < 0)
return ("" + c + variable);
else if (exponent == 0 && c > 0)
return ("" + "+" + c);
else if (exponent == 0 && c < 0)
return ("" + c);

return ("" + c + variable + "^" + exponent);
}
}

最佳答案

简单的解决方案:

String term = "32x^33";
String[] tokens = term.split("\\^");
String coeff = tokens[0].substring(0, tokens[0].length()-1);
String var = tokens[0].substring(tokens[0].length()-1, tokens[0].length());
String exp = tokens[1];
System.out.println("coeff = "+coeff+", var = "+var+", exp = "+exp);

关于java - 通过构造函数从字符串输入中提取多项式变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9752665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com