I am relatively new to the land of Java and google has had no help, this may be a common rookie mistake but I am not exactly sure how to go about debugging. My program is relatively small (1 class) and I figured it couldn't hurt to see if someone could figure out my idiocy. And btw this programs solves quadratics, just for reference <3
My errors (all errors originate from their respective if statements):
error: method quadneggative in class QuadraticFormula cannot be
applied to given types;
error: method quadpositive in class QuadraticFormula cannot be applied to given types;
error: method diszero in class QuadraticFormula cannot be applied to given types;
My program:
import java.lang.*;
import java.util.*;
public class QuadraticFormula {
public QuadraticFormula() {
}
public static void main(String[] args) {
runnermethod();
}
public static double scannermethod()
{
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Please input a value:");
double val = keyboardInput.nextDouble();
return val;
}
public static double dis(double aval, double bval, double cval)
{
double a = aval;
double b = bval;
double c = cval;
double dis = Math.pow(b,2)-(4*a*c);
return dis;
}
public static void diszero(double aval, double bval)
{
double a = aval;
double b = bval;
double quadzero = (-1*b)/(2*a);
System.out.print("Your real solution is: x ="+quadzero);
}
public static void quadpositive(double aval, double bval, double dis)
{
double d = dis;
double a = aval;
double b = bval;
double quadsqr = Math.sqrt(d);
double quadpostop = (-1*b)+quadsqr;
double quadnegtop = (-1*b)-quadsqr;
double quadposall = quadpostop/(2*a);
double quadnegall = quadnegtop/(2*a);
System.out.print("Your real solutions are: x ="+quadposall+","+quadnegall+"i");
}
public static void quadneggative(double aval, double bval, double dis)
{
double d = dis;
double a = aval;
double b = bval;
double quadsqr = Math.sqrt(d*(-1));
double quadpostop = (-1*b)+quadsqr;
double quadnegtop = (-1*b)-quadsqr;
double quadposall = quadpostop/(2*a);
double quadnegall = quadnegtop/(2*a);
System.out.print("Your imaginary solutions are: x ="+quadposall+"i,"+quadnegall+"i");
}
public static void runnermethod()
{
scannermethod();
double a = scannermethod();
double b = scannermethod();
double c = scannermethod();
dis(a, b, c);
double disc = dis(a, b, c);
if(disc < 0)
{
quadneggative();
}
if(disc > 0)
{
quadpositive();
}
if(disc == 0)
{
diszero();
}
}
}
you forgot to add the parameters to the methods
it should be like:
if(disc < 0) {
quadneggative(a,b,disc);
}
if(disc > 0) {
quadpositive(a,b,disc);
}
if(disc == 0) {
diszero(a,b);
}
Related
I have a class Fraction with the arithmetic operations for fractions. Here is an abstract of my class Fraction. (I've included only method of addition.)
package com.company;
import java.util.Scanner;
public class Fraction {
private int num; // numerator
private int denom; // denominator
public Fraction() {
super();
}
public Fraction(int num, int denom) {
super();
this.num = num;
this.denom = denom;
if (denom == 0) {
this.denom = 1;
}
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getDenom() {
return denom;
}
public void setDenom(int denom) {
if (denom > 0) {
this.denom = denom;
}
}
public void inputFraction() {
Scanner innum = new Scanner(System.in);
System.out.println("Input numerator: ");
num = innum.nextInt();
Scanner indenom = new Scanner(System.in);
System.out.println("Input denominator: ");
denom = indenom.nextInt();
}
public String toString() {
return num + "/" + denom;
}
// addition
public Fraction add(Fraction f2) {
int num2 = f2.getNum();
int denom2 = f2.getDenom();
int num3 = (num * denom2) + (num2 * denom);
int denom3 = denom * denom2;
Fraction f3 = new Fraction(num3, denom3);
f3.simplifyFraction();
return f3;
}
}
Now my second task is to make a class Calculator, which aggregates two instances of class Fraction as its attributes and create a complete set of arithmetic operations using instances of the class Fraction as operands. So, if I am correct, I basically have to use those methods from the class Fraction in my Calculator. I've attempted to do that but I do not get any output when I call for method add (from class Calculator) in main().
Here is an abstract of my Calculator class. (I've included only method of addition to give the general idea.)
package com.company;
public class Calculator {
private Fraction f1 = new Fraction();
private Fraction f2 = new Fraction();
private Fraction f;
public Calculator() {
super();
}
public Calculator(Fraction f) {
this.f = f;
}
public void input() {
f1.inputFraction();
f2.inputFraction();
}
public void view() {
f1.toString();
System.out.println("Fraction = " + f1.toString());
f2.toString();
System.out.println("Fraction = " + f2.toString());
}
public Calculator add() {
Calculator f = new Calculator(f1.add(f2));
return f;
}
}
And part of my main():
Calculator m = new Calculator();
m.input();
m.view();
System.out.println("Sum = " + m.add());
I'm assuming there are multiple places where I have gone wrong, so I'd be grateful for some advice.
Your add method is the problem here. It is returning a Calculator object and println calls that object's toString method so the toString method for Calculator is being called. The add method should not return a new Calculator but instead a new Fraction that represents your result. Then the code will print the toString method in your Fraction class which is what you want to display.
public class Calculator {
.
.
.
public Fraction add() {
return f1.add(f2);
}
}
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.
I'm working out a question from a labsheet but i'm only getting 0.0 as answer when running the program. I can't find out what's wrong please help.
The question:
Implement a class Pizza with attribute diameter (in cm), cost_sq_cm (cost per square cm) and area. Its methods are:
• Constructor to create an object of type Pizza with a given diameter and given price_sq_cm.
• Mutator and accessor methods for diameter and cost_sq_cm.
• calcArea to calculate the area of a given pizza.
• getPrice to calculate and return the price of a pizza.
Write a class TestPizza with a main method that declares an object of type Pizza with a user inputted diameter and user-‐inputted cost_sq_cm of a circular pizza, and display the price of the pizza.
The Pizza class:
package Number3;
public class Pizza {
private int diameter;
private float cost_sq_cm;
private double area;
private double price;
public Pizza() //default constructor
{
diameter = 0;
cost_sq_cm = 0;
area = 0;
price = 0;
}
public Pizza(int d,float cost,double a,double p) //overloaded constructor
{
d = diameter;
cost = cost_sq_cm;
a = area;
p = price;
}
public void Constructor() //method
{
Pizza P = new Pizza();
}
public void setDiameter(int d) //mutator
{
d = diameter;
}
public int getDiameter() //accessor
{
return diameter;
}
public void setCost(float c)
{
c = cost_sq_cm;
}
public float getCost()
{
return cost_sq_cm;
}
public double calcArea()
{
area = 3.142 * (diameter * diameter);
return area;
}
public double getPrice()
{
price = area * cost_sq_cm;
return price;
}
public void display()
{
System.out.print("The area is: "+this.price);
}
}
TestPizza:
package Number3;
import java.util.Scanner;
public class TestPizza {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float area = 0;
Pizza P = new Pizza();
int d; float c,a = 0;
System.out.print("Enter a value for the diameter: ");
d = input.nextInt();
P.setDiameter(d);
System.out.print("Enter a value for the cost: ");
c = input.nextFloat();
P.setCost(c);
P.display();
}
}
I'm new to JAVA. Please be lenient.
You should multiply cost per square centimeter times area to get price. You'll get zero if either one is equal to zero. I see where you've set diameter, but not area.
You set diameter, but you don't calculate area when you set it.
public void setDiameter(int d) //mutator; lose this comment. worthless clutter.
{
d = diameter;
area = calcArea();
}
I'd recommend following the Java idiom. Don't write a display() method; better to override toString().
I'd write it this way:
package cruft;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Pizza
* #author Michael
* #link https://stackoverflow.com/questions/28658669/classes-and-objects-getting-0-0-as-answer-when-calculating-price-java
* #since 2/22/2015 12:27 PM
*/
public class Pizza {
private static final int DEFAULT_DIAMETER = 38;
private static final double DEFAULT_COST = 15.0;
private static final double DEFAULT_COST_PER_AREA = 0.013226; // 15 euro for a 38 cm diameter pizza
private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("#.####");
private final int diameter;
private final double costPerArea;
private final double price;
public static void main(String[] args) {
int diameter = ((args.length > 0) ? Integer.valueOf(args[0]) : DEFAULT_DIAMETER);
double costPerArea = ((args.length > 1) ? Double.valueOf(args[1]) : DEFAULT_COST_PER_AREA);
Pizza pizza = new Pizza(diameter, costPerArea);
System.out.println(pizza);
}
public Pizza(int diameter, double costPerArea) {
if (diameter <= 0) throw new IllegalArgumentException("diameter must be positive");
if (costPerArea <= 0) throw new IllegalArgumentException("cost per area must be positive");
this.diameter = diameter;
this.costPerArea = costPerArea;
this.price = this.costPerArea*this.calculateArea();
}
public double getPrice() {
return price;
}
private double calculateArea() {
return Math.PI*this.diameter*this.diameter/4.0;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Pizza{");
sb.append("diameter=").append(diameter);
sb.append(", costPerArea=").append(DEFAULT_FORMAT.format(costPerArea));
sb.append(", price=").append(NumberFormat.getCurrencyInstance().format(getPrice()));
sb.append('}');
return sb.toString();
}
}
For setting a field or another value it is
variable = value;
so
diameter = d;
It looks like your setCost and setDiameter methods need to be changed,
From
d = diameter;
To
this.diameter = d;
Instead of:
System.out.print("The area is: "+this.price);
Use:
System.out.print("The area is: "+this.getPrice());
You need to calculate area as well. So in your main method call it like:
P.calcArea();//to calculate area
You initialised price as 0, when you called new Pizza() and you never called getPrice which is where you calculate the price.
Also change your setter for cost from:
public void setCost(float c) {
c = cost_sq_cm;
}
To
public void setCost(float c) {
cost_sq_cm = c;
}
I implemented two java classes to solve the percolation problem but it throws the following exception
java.lang.NullPointerException
at PercolationStats.<init>(PercolationStats.java:24)
at PercolationStats.main(PercolationStats.java:54)
Program:
public class PercolationStats {
int t=0;
double[] sample_threshold;
Percolation B;
int N1;
public PercolationStats(int N, int T) {
t=T;
N1 = N;
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
public double mean() {
double sum = 0.0;
for(int i=0;i<N1;i++) {
sum += sample_threshold[i];
}
return sum/t;
}
public double stddev() {
double sum = 0.0;
double u = mean();
for(int i=0;i<N1;i++) {
sum += (sample_threshold[i]-u)*(sample_threshold[i]-u);
}
return sum/(t-1);
}
public double confidenceLo() {
return mean()-((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public double confidenceHi() {
return mean()+((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
PercolationStats C=new PercolationStats(N,T);
double mean=C.mean();
double stddev = C.stddev();
double confidenceLo = C.confidenceLo();
double confidenceHi = C.confidenceHi();
System.out.println("mean = "+mean);
System.out.println("stddev = "+stddev);
System.out.println("95% confidence interval = "+confidenceLo+", "+confidenceHi);
}
}
You never initialized double[] sample_threshold;. Hence it is null.
Java will indeed fill a double[] with 0.0 once it is initialized to a known size. You must initialize the array first:
public PercolationStats(int N, int T) {
t=T;
N1 = N;
sample_threshold[i] = new double[T]; // add this line
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
here at 3rd line where you've written double[] sample_threshold;
instead just write double[] sample_threshold= new double[5000];
meaning just initalize the array. Then when you use it in for loop java will only consider the arrays for the times your for loop loops.
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.