java: quadratic equation coefficients | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

java: quadratic equation coefficients

Can you guys explain why the code don't work? :( Help please ax2 + bx + c = 0 -> return one or two roots of the equation if there is any in the set of real numbers -> Input value via System.in -> Output value must be printed to System.out Output format is: -> "x1 x2" (two roots in any order separated by space) if there are two roots -> "x" (just the value of the root) if there is the only root -> "no roots" (just a string value "no roots") if there is no root -> The a parameter is guaranteed to be not zero import java.util.Scanner; //import static java.lang.Math.sqrt; public class QuadraticEquation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double a = scanner.nextDouble(); double b = scanner.nextDouble(); double c = scanner.nextDouble(); double discriminant = Math.pow(b, 2) - 4 * a * c; System.out.print("The equation has "); if (discriminant > 0) { double root1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a); double root2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a); System.out.println("two roots " + root1 + " and " + root2); } else if (discriminant == 0) { double root1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a); System.out.println("one root " + root1); } else System.out.println("no real roots"); } } I need to receive (for example): Input: 2, 5, -3 Output: -3 0.5 Input: 2, 2, 2 Output: no roots

3rd Dec 2021, 12:10 AM
Анастасия Перминова
9 Answers
+ 2
Simple, Scanner use a delimiter which is a regex that acts as a separator, the problem is that the delimiter is by default settled to "\s+" (spaces), so the comma is considered as an invalid character(like a, b, ... , y, z...), and to fix this, just replace the delimiter by another regex with this : Scanner scanner = new Scanner(System.in).useDelimiter("[,\s\n]\s*");
3rd Dec 2021, 5:40 PM
VCoder
VCoder - avatar
+ 1
add this after create Scanner: scanner.useDelimiter( "(>?\s*,\s*)|\s+"); this solution is similar to VCoder, but maches also space before coma
3rd Dec 2021, 9:12 PM
zemiak
0
if input is 2 5 -3 (without comas) change + and - in ( -b - ... ) double root1 = (-b - Math.pow(discriminant, 0.5)) / (2 * a); double root2 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);
3rd Dec 2021, 5:49 PM
zemiak
0
zeniak, the problem is that running the code will cause an error, even if change the + and - 😅
3rd Dec 2021, 5:51 PM
VCoder
VCoder - avatar
0
it works for me how can I simulate it ?
3rd Dec 2021, 5:53 PM
zemiak
0
The error will occur if you input 2, 4, 6 (without my answer)
3rd Dec 2021, 5:54 PM
VCoder
VCoder - avatar
0
comas are necessary?
3rd Dec 2021, 5:55 PM
zemiak
0
Yeah
3rd Dec 2021, 5:55 PM
VCoder
VCoder - avatar
0
edit
4th Dec 2021, 4:55 AM
zemiak