Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Larry Ellison Database Genius Of Oracle

Authors: Craig Peters

1st Edition

0766019748, 978-0766019744

More Books

Students also viewed these Databases questions