Quadratic Equation, cannot figure out syntax error - java

I am working on a school assignment. I am supposed to implement a class and supply the methods getSolution1 and getSolution2. However, I am having 2 issues with my code that I cannot figure out.
Issue #1 is on this line:
solution1= ((-1*b)/> + Math.sqrt(Math.pow(b,2)-(4*a*c)));
The compiler is telling me: Syntax error on token ">", delete this token. I can't figure out if I am doing something wrong on my syntax.
Issue #2 is on the ouput line:
String quadEquation= "The quadratic equation is "+ a + Math.pow(("x"),2) + " + " + b+"x"+ " + " + c+ " =0";
Under the Math.pow I get an error that says: The Method pow is not applicable for the arguments String
Here is my entire code:
public class QuadraticEquation
{
double a;
double b;
double c;
double solution1;
double solution2;
QuadraticEquation (double a, double b, double c){
a= this.a;
b= this.b;
c= this.c;
}
public boolean hasSolution (){
if ((Math.pow(b,2))- (4*a*c)<0){
return false;
}
else
{
return true;
}
}
public double getSolution1 (double a, double b, double c)
{
if (hasSolution){
solution1= ((-1*b) + Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;
return solution1;
}
}
public double getSolution2 (double a, double b, double c){
if (hasSolution){
solution1= ((-1*b) - Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;
return solution2;
}
}
public String toString (double a, double b, double c){
String quadEquation= "The quadratic equation is "+ a + "x^2" + " + " + b+"x"+ " + " + c+ " =0";
return quadEquation;
}
}
Since this is a school assignment, I am looking for guidance on solving this problem.
Thank you.

Your first issue is that you can't use /> together. This is not a proper operation.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
Second issue is because Math.pow requires two numbers. You have a string in there. It would be like trying to get the power of the word apple. You cant do it. You must first convert that string into an int. How to convert a String to an int in Java?

solution1= ((-1*b) + Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;
There is no such thing as a /> in Java.
String quadEquation= "The quadratic equation is "+ a + "x^2" + " + " + b+"x"+ " + " + c+ " =0";
Math.pow requires numbers whereas you were passing the string "x". the symbol "^" is generally used to say to the power of , therefore x^2 is x to the power of 2. I do not think there is a simple solution to write superscript in standard output.
Java cannot understand what to return if the equation has no solution
public double getSolution2 (double a, double b, double c){
if (hasSolution){
solution1= ((-1*b) - Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;
return solution2;
}
return -1; // or throw an exception.
}
returning -1 will fix it.

Related

Getting WA despite writing correct code with the correct output

This is the basic codechef question: Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal, the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction.
''
This is my code:
import java.util.Scanner;
public class Main
{
public static void main(String args[]){
Scanner s= new Scanner(System.in);
double withdraw = s.nextDouble(); double balance = s.nextDouble();
if((withdraw%5==0) && balance>=(withdraw+0.50))
System.out.println("Balance: "+(balance-withdraw-0.50));
else
System.out.println("Balance: "+balance);
}
}
It's giving the correct output still I'm getting a wrong answer
I think you need to check if withdraw > 0.
Beware modulus, floating-point, and comparing floating-point numbers with "=". It is safer to convert the inputs to long (by multiplying by 100 and using Cents instead of $s). That can avoid some nasty rounding errors with >= 0.50, which would now always be exact and look like >= 50. When producing output, you would have to convert to dollars again:
static long dollarsToCents(double dollars) { return (long)(dollars*100); }
static String centsAsDollars(long cents) { return "" + (cents/100) + "." + (cents%100); }
It is unlikely that the problem is due to this, but look at the following example:
double d = 5_000_000_000_000_000.0; // 5 * 10^15
double e = 0.5;
double f = d + e;
System.out.println("" + d + " + " + e + " = " + f);
System.out.println("both are equal?: " + (d == f)); // true
long a = dollarsToCents(d);
long b = dollarsToCents(e);
long c = a + b;
System.out.println("" + a + " + " + b + " = " + c);
System.out.println("both are equal?: " + (a == c)); // false
For increased safety (and if you ever have to handle money in a program), use BigDecimal. However, those are much slower than fixed-size integers such as long.

Implementing the Java comparable interface? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am not sure how to implement a comparable interface into my complex class. I have the following example code that I am using to try and get my head around it. I know it should be something like public double compareTo (Complex o) and something like that but I am not so sure on how to do it. Any suggestions on how i will implement it?:
import java.util.Scanner;
public class Complex implements Cloneable, Comparable {
private double real;
private double imag;
/*
* public Object clone() throws CloneNotSupportedException { Complex
* objClone = new Complex(); objClone.setReal(this.real);
* objClone.setImag(this.imag); return objClone; }
*/
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex(double real) {
this.real = real;
}
public Complex() {
}
public void setReal(double real) {
this.real = real;
}
public void setImag(double imag) {
this.imag = imag;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public void add(Complex num1, Complex num2) {
this.real = num1.real + num2.real;
this.imag = num1.imag + num2.imag;
}
public Complex subtract(Complex num) {
Complex a = this;
double real = a.real - num.real;
double imag = a.imag - num.imag;
return new Complex(real, imag);
}
public Complex multiply(Complex num) {
Complex a = this;
double real = a.real * num.real - a.imag * num.imag;
double imag = a.real * num.imag + a.imag * num.real;
return new Complex(real, imag);
}
public Complex divide(Complex c1, Complex c2) {
return new Complex((c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag),
(c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag));
}
public double absolute() {
return Math.sqrt(real * real + imag * imag);
}
public String toString() {
return this.real + " + " + this.imag + "i";
}
#Override
public Complex clone() throws CloneNotSupportedException {
super.clone();
return new Complex(real, imag);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the first set of complex numbers respectively: ");
double a = in.nextDouble();
double b = in.nextDouble();
Complex c1 = new Complex(a, b);
System.out.print("Enter the second set of complex numbers respectively: ");
double c = in.nextDouble();
double d = in.nextDouble();
Complex c2 = new Complex(c, d);
Complex result = new Complex(c, d);
result.add(c1, c2);
System.out.println("(" + a + " + " + b + "i) + (" + c + " + " + d + "i) = " + result.toString());
System.out.println("(" + a + " + " + b + "i) - (" + c + " + " + d + "i) = " + c1.subtract(c2));
System.out.println("(" + a + " + " + b + "i) * (" + c + " + " + d + "i) = " + c1.multiply(c2));
System.out.println("(" + a + " + " + b + "i) / (" + c + " + " + d + "i) = " + result.divide(c1, c2).toString());
System.out.println("|" + a + " + " + b + "i| = " + c1.absolute());
}
public double compareTo(Complex other) {
return this.getReal() - other.getReal();
}
}
First, the compareTo method of Comparator interface returns int, not double. Second, if you want to compare two double values in Comparator, you should never use a - b pattern. Instead, use predefined Double.compare method:
public int compareTo(Complex other) {
return Double.compare(this.getReal(), other.getReal());
}
This method carefully handles all the special values like -0.0 or NaN which are not very easy to handle manually. Note that similar methods exist for other types: Integer.compare, Long.compare and so on. It's preferred to use them.
Of course it should be noted that there's no natural order for complex numbers. Here you just compare the real parts, completely ignoring the imaginary parts.
From a mathematical standpoint, Complex numbers can't be ordered, and as such aren't a good fit for the the Comparable interface. To quote the wikipedia article:
Because complex numbers are naturally thought of as existing on a two-dimensional plane, there is no natural linear ordering on the set of complex numbers.
There is no linear ordering on the complex numbers that is compatible with addition and multiplication. Formally, we say that the complex numbers cannot have the structure of an ordered field. This is because any square in an ordered field is at least 0, but i2 = −1.
Having said that, there's nothing technically stopping you from implementing this interface. E.g., you can decide that you are sorting by the real part first and by the imaginary part second. Note that the contract of the compareTo method requires you to return an int, not a double. Also, you should define your class as extending Comparable<Complex> instead of a raw Comparable, so you don't have to mess around with casting and runtime type checking:
#Override
public int compareTo(Complex other) {
int realCompare = Double.compare(getReal(), other.getReal());
if (realCompare != 0) {
return realCompare;
}
return = Double.compare(getImag(), other.getImag());
}
EDIT:
The improvements in JDK 8's Comparator interface allow for a much more elegant implementation with the same behavior:
public int compareTo(Complex other) {
return Comparator.comparingDouble(Complex::getReal)
.thenComparingDouble(Complex::getImag)
.compare(this, other);
}
A few points worth noting.
As other answers have noted you generally should only implement Comparable if there's a natural ordering for instances of the class. As there's no natural ordering for complex numbers you likely shouldn't implement Comparable.
If you are going to provide a natural ordering then you should implement Comparable<Complex> to denote comparing to other instances of Complex (rather than comparing to other objects).
A better alternative to implementing Comparable is to provide one or more Comparator objects for your class that can be used to provide as many orderings as you want. For example:
public class Complex {
private double real;
private double imaginary;
public static final Comparator<Complex> COMPARE_BY_REAL =
Comparator.comparingDouble(Complex::getReal);
public static final Comparator<Complex> COMPARE_BY_IMAGINARY =
Comparator.comparingDouble(Complex::getImaginary);
public static final Comparator<Complex> COMPARE_BY_MODULUS =
Comparator.comparingDouble(Complex::getModulus);
private double getModulus() {
return Math.sqrt(real * real + imaginary * imaginary);
}
}
Then the user of the class can choose the ordering that makes sense to the use:
Optional<Complex> closestToOrigin = complexList.stream().min(Complex::COMPARE_BY_MODULUS);

program that gives both the hcf and gcd of two numbers

I'm a beginner, and this is for school. Please help me with this, it's got to be a very simple program that the user enters two numbers and the result is two numbers, one hcf and one gcd.
I wrote the codes separately but I don't know how to combine them.
Go to your GCD program and take the code where you're calculating the GCD and move it into a function:
public int GCD(int a, int b) {
//find GCD
//return GCD
}
And do the same for HCF:
public int HCF(int a, int b) {
//find HCF
//return HCF
}
Then in the main method:
//all the code for prompting the user for input
//and all the code for asking the user for input
//code which you've already written if you wrote these two programs independently already
System.out.println("GCD of " + input1 + " and " + input2 + " is " + gcd(input1, input2));
System.out.println("HCF of " + input1 + " and " + input2 + " is " + hcf(input1, input2));

call a method from another class

I'm in an intro programming class, in the lab that I'm currently working on we have to have two classes and pull the methods from one class, "Energy" and have them run in "Energy Driver."
I'm having trouble calling the methods (testOne, testTwo, testThree) over into "EnergyDriver"
public class EnergyDriver
{
public static void main(String [] args)
{
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + kineticE1);
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + kineticE2);
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + kineticE3);
}
}
public class Energy
{
public static void main(String [] args)
{
public double testOne;
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
}
public double testTwo;
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
}
public double testThree;
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
}
}
You must have only one main method in any one of class. To call a method from another class you can create an object of that class a call their respective method. Another way is by keeping the calling method to be static so you can access that method via Classname.Methodname.
public class EnergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + energy.testOne());
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + energy.testTwo());
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + energy.testThree());
}
}
class Energy
{
public double testOne()
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
public double testTwo()
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
return kineticE2;
}
public double testThree()
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
return kineticE3;
}
}
You can get the value of Kinetic Engergy 1,2,3 by using this code.
You can also use the below code which will use only one method to calculate different values by giving different arguments.
public class EngergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
double mass=25;
double velocity=70;
System.out.println(mass+ " kiolograms, "+velocity+"meters per second: Expected 61250," + " Actual " + energy.testOne(mass,velocity));
}
}
class Energy
{
public double testOne(double mass, double velocity)
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
}
Java programs have SINGLE point of entry and that is through the main method.
Therefore in a single project only one class should have the main method and when compiler will look for that when you run it.
Remember that static methods cannot access non static methods hence main is static therefore it can not access testone two nor three UNLESS you create and object of that type. Meaning in the main method you can have Energy e = new Energy() then access those methods that were not declared with keyword static like e.testone() .
However take note that non static methods can access static methods through Classname.Method name because keyword static entails that only a single copy of that method/variable exists therefore we do not need an object to access it since only one copy exists.
I recommend watching the Java videos from Lynda.com or reading the books Java Head First and Java How To Program (Deitel,Deitel) to give you a boost on your Java knowledge they come with alot of exercises to enhance your knowledge.
Also there are plenty of other questions like this on SO search for them

What does "Type mismatch: cannot convert from null to double" mean?

I'm trying to solve exercise from Art & Science of Java, solution for quadratic equation.
import acm.program.*;
public class QuadraticEquation extends ConsoleProgram {
public void run(){
println("Enter coefficients for quadratic equation");
int a = readInt("Enter first number: ");
int b = readInt("Enter second number: ");
int c = readInt("Enter third number: ");
double result = quadratic(a,b,c);
println("The first solution is: " + result);
}
private double quadratic(int a, int b, int c){
double underSquare = (b*b-4*a*c);
double x = (-b+Math.sqrt(b*b-(4*a*c)))/(2*a);
if (underSquare < 0) {
return null;
} else {
return (x);
}
}
}
I have an error in line:
return null;
saying:
Type mismatch: cannot convert from null to double
I don't really understand what this error, how should I solve this correctly?
You need to understand the difference between primitive types (e.g., double) and boxed object types (e.g., capital-D Double). Whereas Double is a reference to an object (and hence can be null), double is a primitive and can not be null.
The compiler is telling you that you declared the return type of your function to be double and so null can not be converted to a double.
Of course you could "fix" the problem by changing the return type to Double (which would make the null return legal, and cause your primitive doubles to be
auto-boxed into Doubles) but that would not really serve you well. You want a better error handling strategy (of which there are many ... some possibilities are to throw an exception, use an Optional return type, use a flag value such as not-a-number aka Double.NaN).
You are asserting that the method should return a primitive of type double, instead you are returning a null value, which doesn't match the stated contract of the method.
What you want to do here depends entirely on how you want to catch this kind of error and there are a number of different solutions here that would be correct, but throwing a null object isn't one of them.
It's also worth noting that in your shown example:
double underSquare = (b*b-4*a*c);
double x = (-b+Math.sqrt(b*b-(4*a*c)))/(2*a);
if (underSquare < 0) {
return null;
} else {
return (x);
}
should be:
double underSquare = (b*b-4*a*c);
double x = (-b+(Math.sqrt(underSquare)))/(2*a);
return x;
which is equivalent to:
double underSquare = (b*b-4*a*c);
double x = (-b+Math.sqrt(b*b-(4*a*c)))/(2*a);
if (underSquare < 0) {
return double.NaN;
} else {
return (x);
}
but far more readable.
Java is smart enough to know that it shouldn't be taking the square root of a negative number and so if you just return x in both cases the code should run just fine. That said, you should also try to catch any exception here. Since there are a lot of error that could occur in directly evaluating numbers you should try something of this sort:
double underSquare = (b*b-4*a*c);
try{
double x = (-b+(Math.sqrt(underSquare)))/(2*a);
} catch (Exception e){
throw e;
} finally {
return x
}
return x;
Since you seem to will to compute the real solutions of the equation you should probably consider throwing an exception.
You cannot return null because it can be used only with references while you want to return a double, which is a primitive data type
You have few problems in your code from returning null to a double method...I have revised your program compare it against yours and if there is any part that you have questions then add a comment to my answer and I'll do my best to help you.
public static void main(String[] args) {
run();
}
static void run(){
System.out.println("Enter coefficients for quadratic equation");
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter first number: ");
Double a = keyboard.nextDouble();
System.out.println("Enter second number: ");
Double b = keyboard.nextDouble();
System.out.println("Enter third number: ");
Double c = keyboard.nextDouble();
resultParta(a,b,c);
}
public static void resultParta(Double a, Double b, Double c) {
double discriminant = Math.pow(b,2) - 4*a*c;
double answer1 = (-b + Math.sqrt(discriminant))/(2*a);
double answer2 = (-b - Math.sqrt(discriminant))/(2*a);
if(discriminant > 0)
{
System.out.println("answer1: " + answer1);
System.out.println("answer2: " + answer2);
}
else if(discriminant == 0)
{
System.out.println("answer2: " + answer1);
}
else
{
double root1complex = -b/(2*a);
double root1complex2 = Math.sqrt(-discriminant)/(2*a);
System.out.println(root1complex + " + " + root1complex2 + " i ");
System.out.println(" ");
System.out.println(root1complex + " - " + root1complex2 + " i ");
}
}
Why do you check for negative determinant after you take the square root? That makes no sense. Check before you do it.
You return a single double, in spite of the fact that quadratics have two roots. What about the one you don't return?
In that case the results are two complex conjugate roots. You could certainly write a Complex class and return both roots.
You don't check for special cases (e.g. a = 0, b = 0, c =0). You should.
Your equation is implemented in the naive style, ignoring numerical issues.
Bad implementation. Lots of room for improvement.

Categories

Resources