use*_*007 8 java math quadratic
我必须为二次类写一个读方法,其中以ax ^ 2 + bx + c的形式输入二次方.该课程的描述如下:
添加一个读取方法,询问用户标准格式的方程式并正确设置三个实例变量.(因此,如果用户键入3x ^ 2 - x,则将实例变量设置为3,-1和0).这将需要您之前完成的字符串处理.显示按原样输入的实际方程式并正确标记为预期输出.
我能够通过使用字符串操作和if else语句来完成ax ^ 2部分.但我不知道如何处理方程的bx和c部分,因为可能在bx和c前面的符号.这是我如何做ax ^ 2方法的一部分.
public void read()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a quadratic equation in standard format.");
String formula = keyboard.next();
String a = formula.substring(0, formula.indexOf("x^2"));
int a2 = Integer.parseInt(a);
if (a2 == 0)
{
System.out.println("a = 0");
}
else if (a2 == 1)
{
System.out.println("a = 1");
}
else
{
System.out.println("a = " + a2);
}
}
Run Code Online (Sandbox Code Playgroud)
随意编写任何代码作为示例.任何帮助将不胜感激.
以下是如何使用正则表达式执行此操作的示例。到目前为止,只有当方程以 ax^2 + bx + c 格式给出时才能正常工作。可以进一步调整它,以允许更改子项的顺序、缺少的项等。为此,我可能会尝试为每个子项提出正则表达式。无论如何,这应该可以让您有一个总体思路:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class ParseEquation {
static Pattern match = Pattern.compile("([\\+\\-]?[0-9]*)x\\^2([\\+\\-]?[0-9]*)x([\\+\\-]?[0-9]*)");
static String parseEquation(String formula) {
// remove all whitespace
formula = formula.replaceAll(" ", "");
String a = "1";
String b = "1";
String c = "0";
Matcher m = match.matcher(formula);
if (!m.matches()) return "syntax error";
a = m.group(1);
if (a.length() == 0) a = "1";
if (a.length() == 1 && (a.charAt(0) == '+' || a.charAt(0) == '-')) a += "1";
b = m.group(2);
if (b.length() == 0) b = "1";
if (b.length() == 1 && (b.charAt(0) == '+' || b.charAt(0) == '-')) b += "1";
c = m.group(3);
return a + "x^2" + b + "x" + c;
}
public static void main(String[] args) {
System.out.println(parseEquation("2x^2 + 3x - 25"));
System.out.println(parseEquation("-2x^2 + 3x + 25"));
System.out.println(parseEquation("+2x^2 + 3x + 25"));
System.out.println(parseEquation("x^2 + 3x + 25"));
System.out.println(parseEquation("2x^2 + x + 25"));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1148 次 |
| 最近记录: |