This question already has answers here:
What is a StackOverflowError?
(16 answers)
Understanding recursion [closed]
(20 answers)
Closed 3 years ago.
i'm writing a program based on the Quadratic Equation everything looks good to me and there are not syntax or logical errors from what i see and also Eclipse isn't detecting any errors before running.
this is the output from the code:
Exception in thread "main" java.lang.StackOverflowError
at QuadraticEquation.getDiscriminant(QuadraticEquation.java:33)
note it continues like this for about 50 lines or so
public class QuadraticEquation {
private double a;
private double b;
private double c;
public QuadraticEquation() {
double a = 0;
double b = 0;
double c = 0;
}
public QuadraticEquation(double newA, double newB, double newC) {
a = newA;
b = newB;
c = newC;
}
public double discriminant1 = Math.pow(b, 2) - 4 * a * c;
public double discriminant2 = Math.pow(b, 2) - 4 * a * c;
public double getA() {
return getA();
}
public double getB() {
return getB();
}
public double getC() {
return getC();
}
public double getDiscriminant() {
double discriminant = (b * 2) - (4 * a * c);
return getDiscriminant();
}
public double getRoot1() {
double r1 = (-1*b) + Math.sqrt(discriminant1) / (2*a);
return getRoot1();
}
public double getRoot2() {
double r2 = (-1*b) - Math.sqrt(discriminant2) / (2*a);
return getRoot2();
}
public void setA(double newA1) {
a = newA1;
}
public void setB(double newB1) {
b = newB1;
}
public void setC(double newC1) {
c = newC1;
}
}
import java.util.Scanner;
public class TestEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
QuadraticEquation Quadratic = new QuadraticEquation();
System.out.println("Please enter the values of the following variables: ");
System.out.println("a: ");
Quadratic.setA(input.nextDouble());
System.out.println("b: ");
Quadratic.setB(input.nextDouble());
System.out.println("c: ");
Quadratic.setC(input.nextDouble());
if (Quadratic.getDiscriminant() < 0) {
System.out.println("The equation has the following roots:");
System.out.println("The first one is " + Quadratic.getRoot1());
System.out.println("The second one is " + Quadratic.getRoot2());
}
else if (Quadratic.getDiscriminant() == 0) {
System.out.println("The equation has one root:");
System.out.println(Quadratic.getRoot1());
}
else {
System.out.println("The equation has the no real roots");
return;
}
}
}
Your error is an infinite recursion here:
public double getDiscriminant() {
double discriminant = (b * 2) - (4 * a * c);
return getDiscriminant();
}
This function calls itself infinitely until the stack overflows. I believe you wanted to return the variable discriminant instead?
Same for your functions getRoot1, getRoot2, getA, getB, and getC.
Related
This question already has answers here:
Adding char and int
(7 answers)
Closed 3 years ago.
I am a newcomer to Java, and in my code attached bellow I have 2 classes, Start.java and ecuație.java. ecuatie.java calculates the square footage of a quadratic ecuation, but for some reason, the constructor doesn't initialize the values properly. Could you shed some light on me as to why does this happen?
package com.ecuatie;
import com.ecuatie.ecuatie;
public class Start {
public static void main(String[] args) {
ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);
System.out.println(exemplu.delta() + '\n');
System.out.println(exemplu.X1() + '\n');
System.out.println(exemplu.X2() + '\n');
}
}
package com.ecuatie;
import java.lang.Math;
public class ecuatie {
private double a = 0, b = 0, c = 0;
ecuatie(double a, double b, double c) {
this.a = a; this.b = b; this.c = c;
}
public double delta() {
return (b * b) - (4 * a * c);
}
public double X1() {
return (-b + Math.sqrt(delta())) / (2 * a);
}
public double X2() {
return (-b - Math.sqrt(delta())) / (2 * a);
}
}
You're getting that because it's adding the ASCII value of the char.
ASCII value for '\n' is 10. so is is like you + exemplu.delta() with 10.
also you don't need add enter while you are using println().
so you just need to write your code like this.
public static void main(String[] args) {
ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);
System.out.println(exemplu.delta() );
System.out.println(exemplu.X1() );
System.out.println(exemplu.X2() );
}
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
Need a little help figuring out why the last part of my code gives an error. Can anybody tell me what's wrong? I'm working with NetBeans for an intro level programming class and cant figure out the last bit of why this is wrong.
I'm getting the following error:
Cannot find symbol symbol: variable rat04 location: class Rational
package rational;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Rational {
// the numer and denom fields represent a fraction
// CLASS INVARIANTS:
// CI1: denom is not 0,
// CI2: denom is positive,
// CI3: numer and denom are in lowest terms.
private final int numer;
private final int denom;
//toString and toDouble
public String toString() {
return numer + "/" + denom;
}
public double toDouble() {
return 1.0 * numer / denom;
}
//utility method
private static int greatestCommonDivisor(int a, int b) {
int c;
while (b != 0) {
c = a % b;
a = b;
b = c;
}
return Math.abs(a);
}
private static void testGcd() {
System.out.println("");
System.out.println("Test Greatest Common Denominator");
System.out.println("");
for (int i = -21; i < 31; i += 2) {
for (int j = -17; j < 31; j += 3) {
System.out.printf("\n%5d%5d%5d", i, j, greatestCommonDivisor(i, j));
}
}
System.out.println("");
}
public Rational(int numer, int denom) throws ZeroDenomException {
// CI1. No way to fix, must throw exception.
if (denom == 0) {
throw new ZeroDenomException();
}
// CI2. Can fix.
if (denom < 0) {
numer *= -1;
denom *= -1;
}
// CI3. Can fix.
int gcd = greatestCommonDivisor(numer, denom);
if (gcd != 1) {
numer /= gcd;
denom /= gcd;
}
// all class invariants now satisfied, initialize fields:
this.numer = numer;
this.denom = denom;
}
public Rational(int book) throws ZeroDenomException {
//this(integer, 1);
//this(1, book);
this(book, 1);
}
public Rational() throws ZeroDenomException {
this(0);
}
private static void testClass() throws ZeroDenomException {
System.out.println("Rational tests.");
System.out.println("");
System.out.println("Test C-tor");
System.out.println("Expected outcome: 4/25, -4/25, -4/25," + "4/25 17/1, 0/1.");
System.out.println("");
Rational rat01 = new Rational(144, 900);
Rational rat02 = new Rational(-144, 900);
Rational rat03 = new Rational(144, -900);
Rational rat04 = new Rational(-144, -900);
Rational rat05 = new Rational(17);
Rational rat06 = new Rational();
System.out.println("rat01 = " + rat01);
System.out.println("rat02 = " + rat02);
System.out.println("rat03 = " + rat03);
System.out.println("rat04 = " + rat04);
System.out.println("rat05 = " + rat05);
System.out.println("rat06 = " + rat06);
}
public static void main(String[] args) {
System.out.println("Rational class");
System.out.println("Implemented by (My Name)");
try {
testClass();
//testGcd();
} catch (ZeroDenomException ex) {
System.out.println("Zero demon exception in testClass()! (J:H)");
}
System.out.println("");
System.out.println("Try bad input");
try {
Rational rat00 = new Rational(0, 0);
} catch (ZeroDenomException zde) {
System.out.println(" Expected Zero Denominator Exception. " + zde);
} catch (Exception e) {
System.out.println("Should not be a general Exception.");
}
System.out.println("");
System.out.println("");
System.out.println("Test toDouble. Expect 0.16");
System.out.println("rat04 to double: " + rat04.toDouble());
}
}
You declared rat04 in testClass and use it in main. The scopes are different.
You can't use a variable from one scope to another.
You can create a static variable in the class (member variable) to be accessible from both method if you want (but really should not...)
public class Rational {
static Rational rat04;
...
}
Or simply don't print the value in main but in testClass where it belong.
So... this is my first post here on Stack and i'm also new into Java (into programming at all). I'm trying to make a simple commandline app that will calculate employees' profit depending of generated income. Already did it but as i'm learning functional interfaces and lambdas right now, i'd like to try use them. Down below you can find the code.
package BalanceCounter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of employees: ");
int empCounter = input.nextInt();
System.out.println();
List<Employee> employees = new ArrayList<>(empCounter);
for (int i = 0; i < empCounter; i++) {
employees.add(new Employee());
}
for (Employee employee : employees) {
System.out.println("Employee: " + employee.getEmpName()
+ "\nBase salary: " + employee.getEmpBaseSalary()
+ "\nProfit from income: " + employee.getEmpBonus()
+ "\n");
}
}
}
Here's Employee class with getEmpBonus() method in comment block. That's where i've tried to use functional interfaces.
package BalanceCounter;
import java.util.Scanner;
class Employee {
private String empName;
private double empBaseSalary;
private double empIncome;
private double empBonus;
Employee() {
Scanner input = new Scanner(System.in);
System.out.print("Employees name: ");
setEmpName(input.nextLine());
System.out.print("Type basic salary: ");
setEmpSalary(input.nextDouble());
System.out.print("Generated income: ");
setEmpIncome(input.nextDouble());
setEmpBonus();
System.out.println();
}
/*
* Here are all the setters
*/
private void setEmpName(String empName) {
this.empName = empName;
}
private void setEmpSalary(double empBaseSalary) {
this.empBaseSalary = empBaseSalary;
}
private void setEmpIncome(double empIncome) {
this.empIncome = empIncome;
}
private void setEmpBonus() {
if (getEmpIncome() <= 10000)
empBonus = (getEmpIncome() * 3) / 100;
else if (getEmpIncome() > 10000 && getEmpIncome() <= 20000)
empBonus = (getEmpIncome() * 2) / 100;
else empBonus = (getEmpIncome() * 1) / 100;
}
/*
* Time for the getters
*/
String getEmpName() {
return empName;
}
double getEmpBaseSalary() {
return empBaseSalary;
}
private double getEmpIncome() {
return empIncome;
}
double getEmpBonus() {
return empBonus;
}
/*
* double getEmpBonus(Calculation calculation) {
* return empBonus = calculation.calculate(this.empBonus);
* }
*/
}
And the last thing is Calculation interface.
package BalanceCounter;
public interface Calculation {
double calculate(double arg);
}
class CalcBonus implements Calculation{
public double calculate(double empBonus) {
return empBonus;
}
}
Sorry for the long post but wanted to give you all informations i have.
Also if you see some mistakes and bad habits in my code - please let me know. Kind regards.
package training;
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
}
interface RealMath {
double operation(double a, double b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public double operateBinary(int a, int b, RealMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
Calculator cal = new Calculator();
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
IntegerMath multiplication = (a, b) -> a * b;
RealMath division = (a, b) -> a / b;
System.out.println("Add: 40 + 22 = " +
cal.operateBinary(40, 22, addition));
System.out.println("Sub: 120 - 80 = " +
cal.operateBinary(120, 80, subtraction));
System.out.println("Mul: 12 * 12 = " +
cal.operateBinary(12, 12, multiplication));
System.out.println("Div: 478 / 12 = " +
cal.operateBinary(478, 12, division));
}
}
This interface :
public interface Calculation {
double calculate(double arg);
}
has the same contract that DoubleUnaryOperator :
#FunctionalInterface
public interface DoubleUnaryOperator {
double applyAsDouble(double operand);
...
}
So you don't really need to introduce a new interface for this.
You could use the built-in one.
But if you want to really stress on the name and or arguments of the method.
As a general way, look before whether built-in Functional Interfaces could not match to your requirement before creating it.
Suppose now you uncomment your method and you want to use this method :
double getEmpBonus(DoubleUnaryOperator calculation) {
return empBonus = calculation.applyAsDouble(this.empBonus);
}
Without lambda, you have to create a subclass or an anonymous class if you want to pass an implementation that doubles the bonus :
class DoubleBonus implements DoubleUnaryOperator {
public double applyAsDouble(double operand) {
return operand * 2;
}
}
The idea of the lambda is that you could inline the subclass with a lambda expression.
You could so invoke the method in this way :
double doubledBonus = getEmpBonus(empBonus->empBonus*2);
You don't need any longer of the subclass or an anonymous class.
everyone so I'm writting a program that solves quadratics (one doubled root and two doubled roots this seems to work but somehow I can't get it to solve complex roots? any help.
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
//} else if (disc < 0) {
//displayComplexConjugates();
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
//} else {
//System.out.println("Help! Arithmetic has failed!");
//
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
The solution:
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
} else {
// New method
displayComplexRoots(a,b,c);
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
// New method
public static void displayComplexRoots(double a, double b, double c) {
double disc = 4 * a * c - b * b;
double dobleA = 2 * a;
String s = "two roots (" + (-b/dobleA) + "+" + (Math.sqrt(disc)/dobleA) + "i) and ("+ (-b/dobleA) + "" + (-Math.sqrt(disc)/dobleA) + "i)";
JOptionPane.showMessageDialog(null, s);
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
General solution with complex numbers:
public class Complex {
double r;
double i = 0;
public Complex(double real, double imaginary) {
this.r = real;
this.i = imaginary;
}
public Complex(double real) {
this.r = real;
}
public Complex add(Complex c){
return new Complex(r+c.r, i+c.i);
}
public Complex cross(Complex c){
return new Complex(r*c.r - i*c.i, i*c.r + r*c.i);
}
public double getR() {
return r;
}
public double getI() {
return i;
}
#Override
public String toString() {
String result = Double.toString(r);
if (i < 0) {
result += " - " + ((i != -1)?Double.toString(-i):"") + "i";
} else if (i > 0) {
result += " + " + ((i != 1)?Double.toString(i):"") + "i";
}
return result;
}
public Complex[] squareRoot(){
double r2 = r * r;
double i2 = i * i;
double rR = Math.sqrt((r+Math.sqrt(r2+i2))/2);
double rI = Math.sqrt((-r+Math.sqrt(r2+i2))/2);
return new Complex[]{new Complex(rR, rI),new Complex(-rR, rI)};
}
public static Complex[] quadraticsRoot(double a, double b, double c) {
Complex[] result = new Complex(b*b - 4*a*c).squareRoot();
Complex bNegative = new Complex(-b);
Complex divisor = new Complex(1.0d / (2 * a));
for (int j = 0; j < result.length; j++) {
result[j] = bNegative.add(result[j]).cross(divisor);
}
return result;
}
public static void main(String[] args) {
Complex[] sol = quadraticsRoot(1,-10,34);
System.out.println(sol[0]);
System.out.println(sol[1]);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
import java.util.Scanner;
public class LinearDrive {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter value for a: ");
double a= in.nextDouble();
System.out.print("Enter value for b: ");
double b= in.nextDouble();
System.out.print("Enter value for c: ");
double c= in.nextDouble();
System.out.print("Enter value for d: ");
double d= in.nextDouble();
System.out.print("Enter value for e: ");
double e= in.nextDouble();
System.out.print("Enter value for f: ");
double f= in.nextDouble();
Linear linear = new Linear(a,b,c,d,e,f);
System.out.println("X= "+ linear.getX);
System.out.println("Y= "+ linear.getY);
}
}
public class Linear {
private double a;
private double b;
private double c;
private double d;
private double e;
private double f;
public Linear(double a, double b, double c, double d, double e, double f) {
this.setA(a);
this.setB(b);
this.setC(c);
this.setD(d);
this.setE(e);
this.setF(f);
}
public Linear(){
}
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public double getE() {
return e;
}
public void setE(double e) {
this.e = e;
}
public double getF() {
return f;
}
public void setF(double f) {
this.f = f;
}
public boolean isSolvable(){
boolean isSolvable= ((a*d) - (b*c));
if (isSolvable!=0){
isSolvable = true;
}
return isSolvable;
}
public double otherCase(){
double otherCase=((a*d) - (b*c));
if(otherCase==0){
otherCase="The equation has no solution";
}
}
public double getX(){
double x = ((this.e*this.d) - (this.b*this.f)) / ((this.a*this.d) - (this.b*this.c));
return x;
}
public double getY(){
double y= ((a*f) - (e*c)) / ((a*d) - (b*c));
return y;
}
}
I am new on this about doing object oriented programs with asking user
for input. I know I have tons of errors. I need help on how to make my
methods work
Program: ask user to enter a b c d e f and display result. If ad-bc=0
report `The equation has no solution
Errors: != is not defined on boolean The equation has no solution
cannot be converted from string to double, I have tried string can't
make it work. Exception in thread "main" java.lang.Error: Unresolved
compilation problems: getX cannot be resolved or is not a field
getY cannot be resolved or is not a field
This line
this.setA(this.a);
should be
this.setA(a);
Otherwise the getX and getY methods seem to be ok. To call them you need to add (), like this:
System.out.println("X= "+ linear.getX());
To check if the system can be solved you can use a method like this:
public boolean isSolvable() {
return Math.abs(a*b - c*d) > 1e-10;
}
Note that you should never compare floating point numbers with ==. Due to rounding errors results of calculations are almost never exact. The code above uses an interval of 10-10 to check for a zero determinant.