Last active
November 19, 2023 21:35
-
-
Save youssef3wi/3cf6e3155db802e86b60422b7001529f to your computer and use it in GitHub Desktop.
Quadratic Equation Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.regex.Matcher; | |
| import java.util.regex.Pattern; | |
| public class CodingGame { | |
| private static int getValueOfCoefficient(String value) { | |
| if (value != null) { | |
| if (value.isEmpty()) { | |
| return 1; | |
| } else if (value.equals("-")) { | |
| return -1; | |
| } else { | |
| return Integer.parseInt(value); | |
| } | |
| } | |
| return 0; | |
| } | |
| public static void main(String[] args) { | |
| String function = "x²-x+1"; | |
| int x = 2; | |
| Pattern quadrupole = Pattern.compile("((?<xpow>-?\\d*)x²)?((?<x>[+-]\\d*)x)?(?<cnst>[+-]?\\d+)"); | |
| Matcher matcher = quadrupole.matcher(function); | |
| if (matcher.matches()) { | |
| int xpow = getValueOfCoefficient(matcher.group("xpow")); | |
| int xValue = getValueOfCoefficient(matcher.group("x")); | |
| int cnst = getValueOfCoefficient(matcher.group("cnst")); | |
| System.out.println("x²: " + matcher.group("xpow")); | |
| System.out.println("x: " + matcher.group("x")); | |
| System.out.println("constant: " + matcher.group("cnst")); | |
| int result = (xpow * x * x) + (xValue * x) + cnst; | |
| System.out.println("Result: " + result); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment