This question already has answers here:
Passing variable values from another method
(3 answers)
Closed 5 years ago.
I can't seem to grasp this
public static void AreaP(double Dia){
double R = Dia/2.0;
double A = PI * (R * R);
System.out.println("The area is: " + A);
public static void PPSI(double Price){
}
I have to find the price per square inch so I need to pass the area that I solved for in AreaP into the method PPSI and was wondering if there is a way I could do that because I know you can't pass methods into other methods.
public static double A=0;
public static void AreaP(double Dia){
double R = Dia/2.0;
A = PI * (R * R);
System.out.println("The area is: " + A);
System.out.println("The price per square inch is:+PPSI(50))
}
public static double PPSI(double Price){
return Price/A;
}
Making the variable 'A' static and outside the method will allow you to access it from anywhere inside the class or even outside(For.eg, Classname.A )
How about this:
private static final double PI = 3.1416;
public static double areaP(double dia){
double r = dia/2.0;
double a = PI * (r * r);
return a;
}
public static void getPricePerSquareInch(double price){
System.out.print(areaP(75)/price);
}
Related
I'm being asked to pass more arguments to match my constructor but I have no idea what to pass into them.
I have multiple instance variables but only a few of them will be defined by the user (the vertices) and the others are going to defined with their respective methods. If I take everything except my vertices outside of my constructor to solve the error I am left with my final output being left as 0 for most of my reports.
Is my constructor the problem or the parameters in my object at fault?
import java.lang.Math;
public class Triangle {
//instance variables
private double VertAx, VertAy, VertBx, VertBy, VertCx, VertCy;
private double lengthAB, lengthBC, lengthCA;
private double Perimeter, Area;
private double H = Perimeter/2;
//Triangle Constructor
public Triangle(double userVertAx, double userVertAy, double userVertBx, double userVertBy, double userVertCx, double userVertCy, double userlengthAB, double userlengthBC, double userlengthCA, double userPerimeter, double userArea, double userH) {
userVertAx = this.VertAx;
userVertAy = this.VertAy;
userVertBx = this.VertBx;
userVertBy = this.VertBy;
userVertCx = this.VertCx;
userVertCy = this.VertCy;
userlengthAB = this.lengthAB;
userlengthBC = this.lengthBC;
userlengthCA = this.lengthCA;
userPerimeter = this.Perimeter;
userArea = this.Area;
userH = this.H;
}
public double lengthAB(double userVertAx, double userVertAy, double userVertBx, double userVertBy) {
return lengthAB = Math.sqrt( (Math.pow((userVertBx - userVertAx), 2)) + (Math.pow((userVertBy - userVertAy), 2)));
}
public double lengthBC(double userVertBx, double userVertBy, double userVertCx, double userVertCy) {
return lengthBC = Math.sqrt( (Math.pow((userVertCx - userVertBx), 2)) + (Math.pow((userVertCy - userVertBy), 2)));
}
public double lengthCA(double userVertCx, double userVertCy, double userVertAx, double userVertAy) {
return lengthCA = Math.sqrt( (Math.pow((userVertAx - userVertCx), 2)) + (Math.pow((userVertAy - userVertCy), 2)));
}
public void setPerimeter(double userlengthAB, double userlengthBC, double userlengthCA) {
Perimeter = userlengthAB + userlengthBC + userlengthCA;
}
public double getPerimeter() {
return Perimeter;
}
public void setArea(double userlengthAB, double userlengthBC, double userlengthCA, double userH) {
Area = Math.sqrt(userH*(userH-userlengthAB)*(userH-userlengthBC)*(userH-userlengthCA));
}
public double getArea() {
double Area = getArea();
return Area;
}
public String toString() {
return String.format("Vertices: A(%f, %f) B(%f, %f) C(%f, %f)\nSide Lengths: AB=%f BC=%f CA=%f\nPerimeter: %f\nArea: %f", VertAx, VertAy, VertBx, VertBy, VertCx, VertCy, lengthAB, lengthBC, lengthCA, Perimeter, Area);
}
}
public class TriangleTest {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner Vertices = new Scanner(System.in);
System.out.println("Welcome to the Triangle Test enter each coordinate of your three vertices SEPERATELY");
System.out.println("Enter Vertex A X");
Double VAX = Vertices.nextDouble();
System.out.println("Enter Vertex A Y");
Double VAY = Vertices.nextDouble();
System.out.println("Enter Vertex B X");
Double VBX = Vertices.nextDouble();
System.out.println("Enter Vertex B Y");
Double VBY = Vertices.nextDouble();
System.out.println("Enter Vertex C X");
Double VCX = Vertices.nextDouble();
System.out.println("Enter Vertex C Y");
Double VCY = Vertices.nextDouble();
//ERROR
Triangle UserTriangle = new Triangle(VAX, VAY, VBX, VBY, VCX, VCY);
//ERROR ^
UserTriangle.lengthAB(VAX, VAY, VBX, VBY);
UserTriangle.lengthBC(VBX, VBY, VCX, VCY);
UserTriangle.lengthCA(VCX, VCY, VAX, VAY);
UserTriangle.getPerimeter();
UserTriangle.getArea();
System.out.println(UserTriangle.toString());
}
}
I am expecting some way to pass the right parameters into my UserTriangle but I am confused as to how. Thank you for any help anyone can provide. My understanding with classes and objects were good with implementing user input but this one seems so tricky to me considering some of the variables are defined in methods and some are defined by the user.
Constructor called with a mismatched number of arguments
You defined your constructor as accepting 12 arguments, but then you called it with only 6 arguments. This is the error you're referring to. To solve this you have 3 options
Provide all the 12 arguments the constructor needs
Define your constructor as receiving 6 arguments
Refactor (see below for instructions), which is the way to go in my opinion
Reverse the initialization statements in your constructor
To initialize your attributes write this.VertAx = userVertAx instead of userVertAx = this.VertAx; (reverse the statement basically)
This goes for all the other attributes too (userlengthAB, userPerimeter, etc...)
Note
It's better to use the Java naming conventions so you can make the difference say between attributes and classes. Attributes and variables should start with a lowercase and classes with an uppercase.
Edit: Refactoring suggestion
An even better writing is to use less arguments in your constructor. Having too many arguments is considered a code smell and will make your code less readable/maintainable, etc...
To handle that you can encapsulate some concepts in classes. For example you can have
public class Vertex {
private double x;
private double y;
public Vertex(double x, double y) {
this.x = x;
this.y = y;
}
public class TriangleVertices {
private vertexA;
private vertexB;
private vertexC;
public TriangleVertices (Vertex a, Vertex b, Vertex c) {
vertexA = a;
vertexB = b;
vertexC = c;
}
}
public class Triangle {
private TriangleVertices vertices;
// other attributes
// You have now 5 arguments less!
public Triangle(TriangleVertices vertices, // other attributes) {
this.vertices = vertices;
// Initialize other attributes
}
}
Here "this" is a keyword which points the constructor to the variables that are declared in the created class (in your case created class is Triangle). we use "this" keyword when
the variable of parameter has the same name as the variable declared in the created class.For example;
class A {
int NewVar;
A (double NewVar){
this.NewVar = NewVar; //here this.NewVar is pointing to NewVar of type int
}
}
Change this in your code. This might solve your problem.
public Triangle(double userVertAx, double userVertAy, double userVertBx, double userVertBy, double userVertCx, double userVertCy, double userlengthAB, double userlengthBC, double userlengthCA, double userPerimeter, double userArea, double userH) {
this.VertAx = userVertAx;
this.VertAy = userVertAy;
this.VertBx = userVertBx;
this.VertBy = userVertBy;
this.VertCx = userVertCx;
this.VertCy = userVertCy;
this.lengthAB = userlengthAB;
this.lengthBC = userlengthBC;
this.lengthCA = userlengthCA ;
this.Perimeter = userPerimeter ;
this.Area = userArea;
this.H = userH ;
}
I just have a quick question my instructor didn't really go over. His examples aren't helping me.
static double Q1(NormalDistribution distro, double x){
// return the z-score of x in the given distribution
}
It says to return the z-score of x in the given distribution. To not have to do all the math and "reinvent the wheel" each time, we are taught to import the library, I imported it, I'm just confused on how to call the class for the method. Please explain
External Library
package cse115.math;
import java.util.ArrayList;
public class NormalDistribution{
private double standardDeviation;
private double mean;
public NormalDistribution(double standardDeviation, double mean){
this.standardDeviation = standardDeviation;
this.mean = mean;
}
/**
* Creates a normal distribution given a data set.
*/
public NormalDistribution(ArrayList<Double> data){
double sum = 0.0;
for(double value : data){
sum += value;
}
double mean = sum / data.size();
double variance = 0.0;
for(double value : data){
variance += Math.pow(value - mean, 2.0);
}
variance /= data.size();
this.mean = mean;
this.standardDeviation = Math.sqrt(variance);
// yes, this method puts 3 free points on the table for the observant.
}
/**
* Returns the z-score of the provided value. Z-score is the number of standard deviations the value
* is away from the mean.
*/
public double zScore(double value){
return (value - this.mean) / this.standardDeviation;
}
public double getStandardDeviation(){
return this.standardDeviation;
}
public double getMean(){
return this.mean;
}
#Override
public String toString(){
return "{" +
"mean=" + mean +
", standardDeviation=" + standardDeviation +
'}';
}
}
You're going to need to create an instance of the external class within your main method.
NormalDistribution normalDistribution = new NormalDistribution(0,0);
you will then call the static function Q1 through the Classname which holds it, passing the NormalDistribution and the double x.
double value = Cse115.Q1(normalDistribution,1);
Whatever those are supposed to do is up to you, good luck.
I have the following class in java :
public class Percentage
{
private double n;
Percentage (double n )
{
this.n=n;
}
public void setN()
{
this.n=n;
}
public double getN()
{
return n;
}
public double percntage ()
{
return this.n/100;
}
}
this Class Percentage will return a double value, but the problem is we can't make any mathematic operation with values like below:
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p*12; // this is error because the class Percentage in not of type double
}
is there someway to make Percentage of type double ?
That is an error because you are multiplying the Percentage object with double value.
The alternative is
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p.getN()*12;
}
You cannot make the class type double. You can perform your operation in the n value instead.
b = p.getN()*12;
you can't define a class as double, because double is a primitive type. What you can do is what the others user suggested:
p.getN();
It will return the double value you need.
No, you can't make it behave like a double, but (like BigDecimal) you can supply methods for performing the relevant operations.
Since your code seems to imply that n = 10 means 10%, i.e. a factor of 0.10, you could make methods like these:
public double of(double value) {
return value * this.n / 100d;
}
public double add(double value) {
return value * (100d + this.n)) / 100d;
}
and then use it like this:
Percentage p = new Percentage(10);
double input = 55;
double d1 = p.of(input); // 10% of 55 = 5.5
double d2 = p.add(input); // 55 + 10% = 60.5
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I am doing a very basic Complex Numbers class in Java but when I test my add and multiply functions I don't get the results I expect. I don't understand what is wrong or how to fix it.
When I run the program I get the following output:
a+b: ComplexNumber#1540e19d
a*b: ComplexNumber#677327b6
I should get the proper addition and multiplication of two complex numbers (following the rules of complex numbers of course)
Any help would be much appreciated! Thanks in advance.
Here is the code:
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double r, double i) {
real = r;
imaginary = i;
}
public double real() {
return real;
}
public double imaginary() {
return imaginary;
}
public ComplexNumber add(ComplexNumber c) {
double newr = real + c.real();
double newi = imaginary + c.imaginary();
return new ComplexNumber(newr, newi);
}
public ComplexNumber multiply(ComplexNumber c) {
double newr = real*c.real() - imaginary*c.imaginary();
double newi = real*c.imaginary() + imaginary*c.real();
return new ComplexNumber(newr, newi);
}
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(1.0, 2.0);
ComplexNumber c2 = new ComplexNumber(-1.0, 0.5);
String c1plusc2 = c1.add(c2).toString();
String c1timesc2 = c1.multiply(c2).toString();
System.out.println("a+b :" + c1plusc2);
System.out.println("a*b :" + c1timesc2);
}
}
You need to override the toString method in the ComplexNumber class:
#Override
public String toString() {
return real + " + i*" + imaginary;
}
Your .add() & .multiply() methods return a ComplexNumber object. By default,
System.out.println("a*b :" + c1.multiply(c2));
evaluates to
System.out.println("a*b :" + c1.multiply(c2).toString());
The toString() method is inherited from the Object class (since all classes inherit from Object). And since you're not overriding it in the ComplexNumber class, you get the default return value from Object's toString() method:
ClassName#hashCodeOfTheObject
EDIT:
toString() returns a String. Change
ComplexNumber c1plusc2 = c1.add(c2).toString();
ComplexNumber c1timesc2 = c1.multiply(c2).toString();
to
String c1plusc2 = c1.add(c2).toString();
String c1timesc2 = c1.multiply(c2).toString();
Output:
a+b :0.0 + i*2.5
a*b :-2.0 + i*-1.5
I am currently trying to create a class that prints out a rectangle with a height and width 1. I have the program set up (there is a template we are supposed to use) and I incorporated all of the steps. However there is one problem with the return statement on the line "SimpleRectangle(){" it says it is missing a return statement but no matter what I return it still comes up with an error.
public static void main (String[] args){
SimpleRectangle rectangle1=new SimpleRectangle();
System.out.println("The area of radius "+rectangle1.perimeter+" is "+rectangle1.getArea());
}
double height;
double width;
SimpleRectangle(){
height=1;
width=1;
}
double getArea(){
return height*width;
}
double getPerimeter(){
return length+length+width+width;
}
}
This looks like a constructor for a class called SimpleRectange
SimpleRectangle(){
height=1;
width=1;
}
In the code you provide there doesn't seem to be such a class. Make sure your code is included in a class with that name and that it has all the fields you are accessing e.g.
public class SimpleRectangle {
double height;
double width;
double perimeter;
double length;
public static void main(String[] args) {
...
...
}
If your code is in a class with any other name you will get "Invalid method declaration. Return type required"
rectangle1.perimeter is not working because there is no field defined with that name, instead you have a method , therefore you need to call it
this is wrong, you need to do rectangle1.getPerimeter()
rectangle1.perimeter should be rectangle1.getPerimeter()
also you dont have a field called length. it's called height
double getPerimeter(){
return height+height+width+width;
}
the consturctor need to be public
public SimpleRectangle(){
height=1;
width=1;
}
You have several issues with your code it is not compiling
The current error is related to missing class definition, but there will be others.......
Try to not copy and past but to understand what you where missing, class definition, no field declaration for length, wrong call to method ecc.
I have included some public and private declaration I suggest that you study some also what this means...
AND NR 1 TRY TO USE AND IDE AS ECLIPSE, THIS WILL HELP YOU ENORMOUSLY AVOIDING AL OF THESE PROBLEMS AND WHEN YOU LEARN TO DEBUG YOU BECOME A PROGRAMMER., no need for SO, for debugging problems
public class SimpleRectangle {
private double height;
private double width;
public SimpleRectangle() {
this.height = 1;
this.width = 1;
}
public double getArea() {
return height * width;
}
public double getPerimeter() {
return height + height + width + width;
}
public static void main(String[] args) {
SimpleRectangle rectangle1 = new SimpleRectangle();
System.out.println("The area of radius " + rectangle1.getPerimeter() + " is " + rectangle1.getArea());
}
}
In order to use rectangle1.getPerimeter() or rectangle1.getArea(), you need to create a class that looks something like this:
public class SimpleRectangle {
double height;
double width;
SimpleRectangle() {
height = 1;
width = 1;
}
double getArea() {
return height * width;
}
double getPerimeter() {
return 2 * (height + width);
}
}
Then you need to create the object (as shown below) before you can use rectangle1.getPerimeter():
public class MainClass {
public static void main (String[] args) {
SimpleRectangle rectangle1 = new SimpleRectangle();
System.out.println("The area of radius " + rectangle1.getPerimeter() + " is " + rectangle1.getArea());
}
}