二次读取方法

8

我需要为二次方程类编写一个读取方法,其中二次方程的形式为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);
    }
 }

随意编写任何代码作为示例。非常感谢您的帮助。


4
如果给你一个二次方程式是-2x^2+3x-1,或者是-2x^2,或者是-x^2+3,你会怎样处理这些情况? - Makoto
这就是if else语句的作用,我的程序可以处理前两个方程,但我进行了进一步的测试,发现对于最后一个-x^2+3方程无法正常工作,所以我需要为此部分编写更多代码。 - user007
4
我的观点更偏向于边缘情况。你必须非常谨慎地处理它们并加以考虑。最终,你需要对由运算符分隔的字符串的每个部分执行相同的消耗操作。这是一个提示。另一个提示是,如果你访问这个Debuggex链接,你会看到你想做的事情的大致流程(在正则表达式中)。 - Makoto
@harpun:我从未说过正则表达式是正确的...只是它勾勒出了你想要实现的一般流程。 - Makoto
如果说有一个13x^2的话,那这个类还能工作吗?子项会如何工作? - user007
显示剩余2条评论
3个回答

2
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Mini {

    public static void main(String[] args) {
        int a = 0;
        int b = 0;
        int c = 0;

    String formula = " -x^2 + 6x - 5";
    formula = formula.replaceAll(" ", "");

    if (!formula.startsWith("+") && !formula.startsWith("-"))
        formula = "+" + formula;

        String exp = "^((.*)x\\^2)?((.*)x)?([\\+\\s\\-\\d]*)?$";
        Pattern p = Pattern.compile(exp);
        Matcher m = p.matcher(formula);

        System.out.println("Formula is " + formula);
        System.out.println("Pattern is " + m.pattern());

        while (m.find()) {
            a = getDigit(m.group(2));
            b = getDigit(m.group(4));
            c = getDigit(m.group(5));
        }

        System.out.println("a: " + a + " b: " + b + " c: " + c);

    }

    private static int getDigit(String data) {
        if (data == null) {
            return 0;
        } 
        else 
        {

            if (data.equals("+"))
            {
                return 1;
            }
            else if (data.equals("-"))
            {
                return -1;
            }
            else
            {
                try
                {
                    int num = (int) Float.parseFloat(data);
                    return num;
                }
                catch (NumberFormatException ex)
                {
                    return 0;
                }
            }
        }
    }
}

嗨Orak,感谢你的帮助。我测试了你的程序,当输入像x ^ 2 + x-3这样的二次方程时,它似乎无法正常工作。当出现这种类型的二次方程时,该类必须将a和b设置为1。 - user007
如果没有找到明确的+,请在开头添加一个显式的+...感谢您的纠正 :) - orak

1

通过正则表达式:

sub quadParse {
    my ($inputStr) = @_;
    my $str = "+".$inputStr;        # as the first needn't have a sign
    $str =~ s/\s+//g;               # normalise
    my $squared = $1 if ($str =~ m/([+-][0-9])*x\^2/);
    my $ex = $1 if ($str =~ m/([+-][0-9]*)x(?!\^)/);
    my $const = $1 if ($str =~ m/([+-][0-9]+)(?!x)/);
    return "${squared}, ${ex}, ${const}";
}

用于字符串解析的Perl。

那好吧:

public static String coeff(String str, String regex) {
    Pattern patt = Pattern.compile(regex);
    Matcher match = patt.matcher(str);
    // missing coefficient default
    String coeff = "+0"; 
    if(match.find()) 
        coeff = match.group(1);
    // always have sign, handle implicit 1
    return (coeff.length() == 1) ? coeff + "1" 
        : coeff;
}
public static String[] quadParse(String arg) {
    String str = ("+" + arg).replaceAll("\\s", "");
    String quad = coeff(str, "([+-][0-9]*)x\\^2" );
    String ex = coeff(str, "([+-][0-9]*)x(?!\\^)");
    String cnst = coeff(str, "([+-][0-9]+)(?!x)" );
    return new String[] {quad, ex, cnst};
}

在ideone中测试Java代码

这些程序可以处理任意顺序的公式,无论第一个项是否有初始符号,并且可以正确处理缺失的项。Perl版本没有将'+'修复为'+1'等,也没有为缺失的项提供显式的'0',因为我时间不够了。


1
这是一个使用正则表达式的示例。目前,只有当方程以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"));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接