So my issue is that I cannot use my global variables (a,b,c) in my arguments. I need to be able to use them in my boolean function and double function. What am I doing wrong? How can I fix this?
public class triareamain extends javax.swing.JFrame {
double a, b, c;
public void DisplayError() {
side1input.setText("Error");
side2input.setText("Type");
side3input.setText("+ Integers");
}
public double areaCal(double a, double b, double c) {
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
public static boolean isValid(double a, double b, double c) {
if (a > b + c || b > a + c || c > a + b) {
return true;
} else {
return false;
}
}
private void calculatebuttonActionPerformed(java.awt.event.ActionEvent evt) {
try {
a = Double.valueOf(side1input.getText());
b = Double.valueOf(side2input.getText());
c = Double.valueOf(side3input.getText());
boolean area = isValid();
if (area == false) {
double finalarea = areaCal();
} else {
DisplayError();
}
} catch (NumberFormatException e) {
side1input.setText("Error");
side2input.setText("Type");
side3input.setText("+ Integers");
}
a, b, and c are not global variables. Java doesn't have that concept. They are fields of class triareamain.
However you also created parameters of the same name, so those names are shadowing the fields.
If you wanted the areaCal() method to use the fields directly, remove the parameters:
public double areaCal() {
If you want the method to use the parameters, then pass values in the call:
double finalarea = areaCal(a, b, c);
If you keep the parameters, I highly recommend that you rename either the fields or the parameters. Shadowing of variable names is very confusing to the programmer, and will in high probability be the cause of bugs.
Related
Suppose i have 2 interface which is
interface add{
void add2No(float a, float b);
}
and
interface Minus{
void Minus2No(float a, float b);
}
then on the main method, i already overide the method which is
public class Count implements Add, Minus {
public static void main(String[] args) throws IOException{
//declare var
float a, b;
String temp;
//create object
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Count obj = new Count();
//User Input
System.out.print("Enter your first Number : ");
temp = br.readLine();
a = Float.parseFloat(temp);
System.out.print("Enter your second Number : ");
temp = br.readLine();
b = Float.parseFloat(temp);
System.out.println("Value of " +a+ " + " +b+ " is : " +obj.Totaladd(float a, float b));
System.out.println("Value of " +a+ " + " +b+ " is : " +obj.TotalMinus(float a, float b));
}
#Override
public void Add2No(float a, float b) {
float TotalAdd = a + b;
}
#Override
public void Minus2No(float a, float b) {
float TotalMinus = a - b;
}
}
Am i using the correct implementation for interface? why there's error when i try to print out the TotalAdd and TotalMinus?
Yes. Because you don't return the results. Currently both methods are void. You could change that. Like,
interface Add {
float add2No(float a, float b);
}
interface Minus {
float minus2No(float a, float b);
}
And then
#Override
public float add2No(float a, float b) {
return a + b;
}
#Override
public float minus2No(float a, float b) {
return a - b;
}
There are three wrong places.
The first wrong place:
Because Java is case sensitive.
The name of your interface method is called add2No, but the name of
your implementation is called Add2No
The second wrong place:
There is a problem with your method parameter passing and the way of
calling. I did not see the Totaladd and Totaladd methods defined in
your Count object.
If you adjust the case, there should only be add2No and Minus2No
methods in Count object.
You need to adjust the name of one of them, and do not pass the type when passing parameters.
For example: obj.Totaladd(float a, float b) should be obj.Totaladd(a, b)
The third wrong place:
If you need to call the method to get the value for calculation, you must adjust the type of the method, it should not be void
I make a class Figure then two subclasses from it. Figure super class have a method named are(). this is the all class.
public class Figure
{
public double a, b;
public Figure(double a,double b) {
this.a = a;
this.b = b;
}
public double are() {
return 0;
}
}
public class Rectangle extends Figure
{
Rectangle(double a, double b) {
super(a,b);
}
double area (){
return this.a*this.b;
}
}
class Triangle extends Figure
{
Triangle(double a, double b) {
super(a,b);
}
// override area for right triangle
double area () {
return a * b / 2;
}
}
to easy print outpute I make
public void toastM(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
now I use this code
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
toastM("are..... " + figref.are());
figref = t;
toastM("are..... " + figref.are());
figref = f;
toastM("are..... " + figref.are());
expected values are 45 40 0
but it come 0 0 0
The parent class has a method called
double are()
the child classes
double area()
so it's not overridden
The functions you are overriding in both Rectangle and Triangle are called area AND NOT are as in the Figure class
You are calling the are() function of the super class Figure, not the area() function the subclass.
I need some help with a program that i am trying to create. This is a Quadratic Equation Formula, where i have 2 classes.
The only issue that i am getting is code
"QuadraticEquation Equation = new QuadraticEquation(a, b, c);"
I am getting the error that says:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type TestQuadraticEquation is accessible. Must qualify the allocation with an enclosing instance of type TestQuadraticEquation (e.g. x.new A() where x is an instance of TestQuadraticEquation).
at TestQuadraticEquation.main(TestQuadraticEquation.java:12)
This error is occurs at line 12 (code above) and i need to find out what is wrong with that section.
public class TestQuadraticEquation
{
public static void main (String [] args)
{
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.println("Please enter the coefficients a, b and c in the order: ");
double a = scan.nextDouble();
double b = scan.nextDouble();
double c = scan.nextDouble();
QuadraticEquation Equation = new QuadraticEquation(a, b, c);
if (Equation.getDiscriminant() > 0)
{
System.out.println("The roots of the equations are " + Equation.getRoot1()
+ " and " + Equation.getRoot2());
}
else
{
System.out.println("The equation has no roots.");
}
}
class QuadraticEquation
{
private double a;
private double b;
private double c;
QuadraticEquation()
{
a = 0;
b = 0;
c = 0;
}
QuadraticEquation (double newA, double newB, double newC)
{
a = newA;
b = newB;
c = newC;
}
public double getA()
{
return a;
}
public double getB()
{
return b;
}
public double getC ()
{
return c;
}
public double getDiscriminant()
{
return (Math.pow(b,2) - 4 * a * c);
}
public double getRoot1()
{
return ((-b + Math.sqrt(getDiscriminant())/(2 * a)));
}
public double getRoot2()
{
return ((-b - Math.sqrt(getDiscriminant())/(2 * a)));
}
}
}
Here you are trying to create an instance of inner class which is QuadraticEquation class. QuadraticEquation class lies inside TestQuadraticEquation so, in order to create instance you can either declare your QuadraticEquation as static class please refer to the link: problem creating object of inner class in java
Other choice is to seperate the class such that QuadraticEquation.java and move the code of QuadraticEquation class there. That way it is no longer inner class.
Also, the other choice would be like the compiler suggested you create instance of TestQuadraticEquation and then from there you can create new object of QuadraticEquation which can be done by:
QuadraticEquation Equation = new TestQuadraticEquation(). new QuadraticEquation(a, b, c);
The purpose of this program is to print
the number of solutions and the solution(s) to a quadratic function,
entered by the user.
The problems here is that I get errors for having private variables,
why is this? Also for my constructor it states that my variables cannot be resolved even though
they are established in the main method. Finally, my variables will pass to the main method or to the "toString" method for use
in the main method.
This is for a school assignment and my professor requires that I use the "toString" method as well as have private variables. I apologize in advance for any formatting mistakes and for the large question, for I am new
to this site.
import java.util.Scanner
public class QuadraticSolver
{
private static Scanner in;
public static void main(String[]args)
{
QuadraticSolver qs = new QuadraticSolver();
in = new Scanner(System.in);
private double a;
private double b;
private double c;
System.out.println("Enter coefficients for quadratic function. ");
a = in.nextDouble();
b = in.nextDouble();
c = in.nextDouble();
qs.getRoot1(a,b,c);
qs.getRoot2(a,b,c);
qs.numOfSolutions(a,b,c);
System.out.println("Your quadratic function is " + a + "x^2 + " + b + "x + " + c);
System.out.println(qs.toString());
}
public QuadraticSolver()
{
a = 0;
b = 0;
c = 0;
}
public double getRoot1(double a,double b,double c)
{
private double root1;
root1 = (-b + Math.sqrt(Math.pow(b,2) - 4*a*c)) / (2*a);
return root1;
}
public double getRoot2(double a,double b,double c)
{
private double root2;
root2 = (-b + Math.sqrt(Math.pow(b,2) - 4*a*c)) / (2*a);
return root2;
}
public int numOfSolutions(double a,double b,double c)
{
private int sol = 0;
private double d;
d = Math.pow(b,2) - 4*a*c;
if(d > 0)
{
sol = 2;
}
else if(d == 0)
{
sol = 1;
}
else if(d < 0)
{
sol = 0;
}
return sol;
}
public String toString()
{
return "There are(is) " + sol + " solution(s). x = " + root1 + " x = " + root2;
}
}
You should move the variables to the class level:
public class QuadraticSolver {
private double a;
private double b;
private double c;
...
}
Next, you need to access the variables that belong to the object qs:
public static void main(String[]args)
{
QuadraticSolver qs = new QuadraticSolver();
in = new Scanner(System.in);
System.out.println("Enter coefficients for quadratic function. ");
qs.a = in.nextDouble();
qs.b = in.nextDouble();
qs.c = in.nextDouble();
...
}
And finally, you should remove the variables from the methods getRoot1(), etc. This is because each method can access the variables a,b,c belonging to the object itself. Thus:
public double getRoot1()
{
double root1 = (-b + Math.sqrt(Math.pow(b,2) - 4*a*c)) / (2*a);
return root1;
}
And at the call sites:
public static void main(String[]args)
{
...
double root1 = qs.getRoot1();
double root2 = qs.getRoot2();
int numsol = qs.numOfSolutions();
...
}
Private instance variables belong to a class. When you create an object that is an instance of a class, the object may have instance variables that belong to the object; if you create multiple instances of a class, each of those instances (objects) has its own set of instance variables. You declare those in the class:
public class QuadraticSolver
{
private static Scanner in;
private double a; // instance variables
private double b;
private double c;
Now, to access those variables, you need to have an object. If you're in a non-static method inside the class, or in a constructor for the class, the method will work with an object called this, so you could say this.a or just a to get at that variable. If you're outside the class, or in a static method in the class (including main), you need to tell it what object you're working with. In your program, your main method has an object qs that is a QuadraticSolver, and you can get at that object's instance variables by saying qs.a, qs.b, etc.
Variables declared inside a method are local variables. They're for use only within that method. They don't declare instance variables for an object. You can't use the keyword private on them, because that keyword is only for instance variables (and other things that aren't variables). You can't use the variables outside that method. If you declare them in an inner set of curly braces, you can't use them outside the curly braces. If you declare a local variable that's the same name as an instance variable, there's no connection between the two.
This is my assignment,
a) Write a quadraticFunction that represents a quadratic ax^2 + bx + c with int coeffients a, b, c. Provide a constructor with 3 int parameters for a, b, c. Provide a method double valueAt(double x) returns the value of this quadratic function at x. Also provide a toString method.
b) override the equals method quadraticmethod class. two quadraticfunction should be considered equal if their respective coeffiecients are equal
c) Make the function objects comparable. The compareTo should first compare 1 if equal compare b if equal compare c
d) Define a comparator class for comparing two QuadraticFunction objects. Provide two constructors: a no-argss constructor and a constructor that takes 1 double parameter. When a comparator is created by the no-args constructor, it should compare two quadraticFunction based on their values at x = 0; when a comparator is created by the constructor with a parameter x, it should compare quadraticFunction based on their values at x
Here's my code
I need help with part D, I don't know how to do some of it
public class Ex4
{
int a;
int b;
int c;
public Ex4(int x, int y, int z)
{
a = x; b=y; c=z;
}
public String toString()
{
String X="";
X= X+a+"x^2"+b+"x"+ "+" + c;
return X;
}
public double valueAt(double x)
{
return (a*x*x+b*x+c);
}
//////// Part B
public boolean equals( Ex4 qf )
{
return(this.a==qf.a && this.b==qf.b && this.c==qf.c);
}
/////Part c
// public int compareTo(Ex4 other)
// {
// if (a.equals(other.a))
// {
// if (b.equals(other.b))
// return c.compareTo(other.c);
// return b.comapreTo(other.b);
// }
// return a.compareTo(other.a);
// }
public int compareTo(Ex4 other)
{
if (a > other.a)
return 1;
else if (a < other.a)
return -1;
else if (b > other.b)
return 1;
else if (b < other.b)
return -1;
else if (c > other.c)
return 1;
else if (c < other.c)
return -1;
else
return 0;
}
////Part d
public static void main(String[] args)
{
System.out.println(new Ex3(1, -5, 6));
}
}
Also in the uncomment the area of code under part c, it says int cannot be dereferenced on line 29, 31, 32,33, and 35
Thanks for the help
You can't call methods on primitives, plain and simple.
A better option is to use Integer's static method, Integer.compare(int a, int b) to compare two ints.
First, writing a custom Comparator isn't too terribly difficult; you need to understand the basic structure of one.
Here's the idea: it reads kind of like you're writing a Comparable entity.
class CustomComparator implements Comparator<Ex4> {
#Override
public int compare(Ex4 left, Ex4 right) {
// Compare the entities as specified by the assignment
}
}
Then, you need to accept that as a constructor argument. That, I leave as an exercise to the reader.
Now, to the syntax issue: you're treating primitive int as an Integer, which does have an equals method on it. Primitives aren't objects, hence they can't be dereferenced. You'll want to use the normal equivalence operators (==, >, <) in this situation. You have this already solved in your second-defined compareTo method.
EDIT: After re-reading your requirements, I'm starting to think that your primitive fields are not the right way to go. You should:
Change your fields from int to Integer
Implement Comparable<Ex4> on your entity class
Rely on the default behavior of compareTo() for Integer; that is, your commented code should "just work" (save for the misspell when comparing against C)
Move the secondary compareTo to its own Comparator entity, as described above.
Try this
import java.util.Comparator;
public class Ex4Comparator implements Comparator<Ex4> {
private double x = 0.0;
public Ex4Comparator() {
}
public Ex4Comparator(double x) {
this.x = x;
}
#Override
public int compare(Ex4 o1, Ex4 o2) {
return Double.compare(o1.valueAt(x), o2.valueAt(x));
}
}
Also your equals method doesn't override Object's equals method. You may want to change it to something like
#Override
public boolean equals(Object o) {
if (o instanceof Ex4) {
Ex4 other = (Ex4)o;
return (a == other.a && b == other.b && c == other.c);
}
return false;
}