二次读取法 [英] Quadratic Read Method
问题描述
我必须为一个二次类编写一个read方法,其中以ax ^ 2 + bx + c的形式输入一个二次数.该类的描述是这样的:
I have to write a read method for a quadratic class where a quadratic is entered in the form ax^2 + bx + c. The description for the class is this:
添加一个read方法,该方法要求用户提供标准格式的方程式,并正确设置三个实例变量. (因此,如果用户键入3x ^ 2--x,则将实例变量设置为3,-1和0).这将需要您之前完成的字符串处理.显示输入的实际方程式,并正确标记为预期输出.
Add a read method that asks the user for an equation in standard format and set the three instance variables correctly. (So if the user types 3x^2 - x, you set the instance variables to 3, -1, and 0). This will require string processing you have done before. Display the actual equation entered as is and properly labeled as expected output.
我能够通过使用字符串操作和if else语句来完成ax ^ 2部分.但是我不确定如何处理方程式的bx和c部分,因为符号可能在bx和c前面.这是我做方法的ax ^ 2部分的方法.
I was able to do the ax^2 part by using string manipulation and if else statements. But I am not sure how to do the bx and c parts of the equation because of the sign that could be in front of bx and c. Here is how I did the ax^2 part of the method.
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);
}
}
随意编写任何代码作为示例. 任何帮助将不胜感激.
Feel free to write any code as an example. Any help would be greatly appreciated.
推荐答案
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;
}
}
}
}
}
这篇关于二次读取法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!