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:
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.
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;
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With