Question: Java Programming Question. I am writing a code to calculate the roots of the quadratic equation based on the values of the coefficients A, B,

Java Programming Question.

I am writing a code to calculate the roots of the quadratic equation based on the values of the coefficients A, B, and C. I am supposed to enter 5 values for each coefficient, and the output should be five different answers (see example) using a for loop and if else statements. However, when I run my code, I am only able to enter one value for each coefficient and the output is one answer repeated five times. How do I fix this? My code is below.

For example enter the following for A, B, and C:

A B C

5 2 2

0 0 4

0 3 6

1 2 1

2 5 2

import java.util.Scanner; public class Quatratic { public static void main (String [] args) { int i, CoeffA, CoeffB, CoeffC; double Disc, X1, X2; Scanner sc = new Scanner (System.in); //Read in coefficients A, B, and C. System.out.println ("Enter the five coefficients for each A, B, and C"); CoeffA = sc.nextInt(); CoeffB = sc.nextInt(); CoeffC = sc.nextInt(); //Calculate discriminant. Disc = (CoeffB * CoeffB) - (4 * CoeffA * CoeffC); //For loop. for (i = 0; i < 5; i++) { // If disciminant and coefficient A are greater than zero, calculate the two roots. if (Disc > 0 && CoeffA > 0) { X1 = CoeffB + Math.sqrt (Disc) / (2 * CoeffA); X2 = CoeffB - Math.sqrt (Disc) / (2 * CoeffA); System.out.println ("The equation has roots " + X1 + " and " + X2); } //If coefficient A and B are equal to zero, there are no roots. else if (CoeffA == 0 && CoeffB == 0) { System.out.println ("The equation has no roots"); } //If coefficient A is equal to zero, calculate the single root. else if (CoeffA == 0) { X1 = - CoeffC / CoeffB; System.out.println ("The equation has a single root equal to " + X1); } //If discriminant is less than zero, there are no real roots. else if (Disc < 0) { System.out.println ("The equation has no real roots (imaginary)"); } //If discriminant is equal to zero, calculate the two roots. else if (Disc == 0) { X1 = - CoeffB / (2 * CoeffA); System.out.println ("The equation has two roots equal to " + X1); } } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!