In: Computer Science
Create a new folder called CSCI130_A3_yourname. Create all of the files indicated below within this folder.
For this assignment you will be creating a total of 2 classes that meet the definitions below. This assignment will allow the user to enter in the coefficients for a polynomial function of degree 2. The user will then be asked to enter a number. The program will use that number as an argument to the function, and will print the corresponding function value.
Keep in mind that a second degree polynomial function in general form looks like:
f(x) = ax2 + bx + c (here 'a' is the coefficient of the quadratic term, 'b' is the coefficient of the linear term, and 'c' is the constant)
Refer to the image at the bottom of this page to get a better understanding of the logic flow.
CLASSES:
CLASS DEFINITIONS:
class Polynomial
Data (instance variables) - all have private access
Methods (behaviors) - all have public access
constructor:
constructPolynomial:
functionValue:
displaySelf:
class Assignment3
Methods
public static void main(String[] args):
After writing the code, do the following:
Code in Java:
class Polynomial
{
private double quadraticCoefficient;
private double linearCoefficient;
private double constant;
Polynomial()
{
constructPolynomial();
//constructor calls this instance method
}
public void constructPolynomial()
{
Scanner sc = new
Scanner(System.in); //to input values from user
System.out.println("Enter
quadraticCoefficient: ");
quadraticCoefficient =
sc.nextDouble();
System.out.println("Enter
linearCoefficient: ");
linearCoefficient =
sc.nextDouble();
System.out.println("Enter constant:
");
constant = sc.nextDouble();
}
public double functionValue(double arg)
{
double v1 =
quadraticCoefficient*quadraticCoefficient*arg;
return((quadraticCoefficient*quadraticCoefficient*arg) +
(linearCoefficient*arg) + (constant));
}
public void displaySelf()
{
System.out.println(quadraticCoefficient + "x2" + " + " +
linearCoefficient + "x + " + constant);
}
}
public class Assignment3{
public static void main(String[] args)
{
Polynomial poly = new
Polynomial();
poly.displaySelf();
System.out.println(poly.functionValue(3));
//since not mentioned in question, function value - 3 is fed
hereitself. However, if required to be taken from user, the same
//Scanner function used earlier for taking the coefficients can be
used to take this value here itself.
}
}