Your task in this homework is to compute the roots of a quadratic, using the quadratic formula. Your program should read in three double values, the coefficients of the x-squared term, the linear term and the constant term respectively. These values will be separated by blanks in the test input. It should compute the two real roots and display them, one to a line. The first root displayed should be the one where you add the square root of the discriminant. You may assume that the quadratics tested will all have real roots. These roots should be displayed to exactly 4 places past the decimal point, with a leading zero shown before the decimal point if it is between -1.0 and 1.0. Your program should display a single blank line as a prompt to make it possible to type in numbers while you are testing the program using BlueJ and to test it on educate when you turn it in.
If the values input, in bold, are:
1.0 4.0 3.0
The output would be:
-1.0000
-3.0000
Similarly, if the values input, in are:
1.0 2.0 1.0
The output would be:
-1.0000
-1.0000
import static java.lang.System.*;
import java.util.Scanner;
import static java.lang.Math.*;
public class Quadratic
{
public static void main(String[] args)
{
//Declare and Initialize Scanner
Scanner scan = new Scanner(in);
//Read in Values
double values = scan.nextDouble();
//Convert double values to String str1
String str1 = values.toString();
//Separate Values
String blankLoc = str1.indexOf(' ');
double a = values.substring(0, blankLoc);
double b = values.substring(blankLoc, blankLoc);
double c = values.substring(blankLoc + 1);
//Discriminant: (b*b) - (4*a*c)
double disc = Math.sqrt((b*b)-(4*a*c));
//Find the Roots
double root1 = (-b + disc)/(2*a);
double root2 = (-b - disc)/(2*a);
//Display Answers
DecimalFormat fmt1 = new DecimalFormat("0.0000");
out.println(fmt1.format(root1));
out.println(fmt1.format(root2));
}
}
The first error that I am encountering is that "double cannot be dereferenced"
Another issue that I have, the three numbers are entered in by the user on one line. Then I need to separate these numbers into 3 separate numbers so that they can be used in the quadratic formula. My problem is that I am not sure how to separate the numbers. I know that I need to use blankLoc but do not really know how to use it correctly(i don't think). If you look in my code under the //Separate Values comment, you will see what I am trying to do. Any suggestions?
Please help me.
Thank You,
Roaster

New Topic/Question
Reply




MultiQuote









|