Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
This is a simple question, but my AP Comp Sci book just doesn't explain it well enough and you guys are always useful.
What is the basic way of creating a custom class in Java and creating methods within that class, then later calling those methods. I know its simple but I can't find a good explanation anywhere
It seems like you need a better understanding of OOP. So, let's create a class and a test client to help you. We will create a class and a test client (or driver) to compute electrical potential. Please note this example is from Introduction to Programming in Java by Robert Sedgewick and Kevin Wayne (an excellent book I highly recommend).
First we create a Charge class:
/*
Separate classes must be in the same directory as main method or must invoke
classpath
*/
public class Charge {
// first declare instance variables which are usually private
private final double rx;
private final double ry;
private final double q;
/* A class contains constructors that are invoked to create objects from a
class blueprint. Constructor declarations look like method declarations
-except that they use the name of the class and have no return type.
Constructors must use the exact name of the class, case sensitive.
Classes and Constructors are capitalized - methods are camelCase.
*/
// Constructor
public Charge(double x0, double y0, double q0) {
rx = x0;
ry = y0;
q = q0;
}
/*
The method to compute electrical potential which is defined by the equation
V = kq/r
*/
public double potentialAt(double x, double y) {
double k = 8.99e09; // Electrostatic Constant that k=8.99 X 10^9 Nm^2/C^2 (N = Newtons, m = meters, C = Coloumbs)
// r = delta x - delta y
double dx = x - rx; // delta x for distance
double dy = y - ry; // delta y for distance
return k*q/Math.sqrt(dx*dx + dy*dy); // Computation using distance formula
}
}
This would be the API to use this class. An important concept in Java programming
is that you do not need to know how a data type is implemented to be able to use it.
public class Charge
This is the constructor:
Charge(double x0, double y0, double q0)
These are instance methods. The most important difference between a variable of
reference type vs primitive type is that you can use reference type variables
to invoke methods that implement data type operations.
double potentialAt(double x, double y)
String toString()
The two parts of using this class would be:
1. Create an object
ClassName object = new ClassName (invoke Constructor)
--------- ------ --- --------- -----------------
Charge c = new Charge (2.2, 3.4, 7.2)
2. Use instance methods on object
c.potentialAt(2.3, 4.2)
This would be the client (or driver) that could be used with this class:
import java.util.*;
public class ChargeClient {
public static void main(String[] args) {
// Using a scanner object to get values
System.out.println("Please enter an X Value");
Scanner in = new Scanner(System.in);
double x = in.nextDouble();
System.out.println("Please enter a Y Value");
double y = in.nextDouble();
/*
1. Instantiate objects c1 and c2
ClassName object = new ClassName (invoke Constructor)
--------- ------ --- --------- -----------------
Charge c = new Charge (2.2, 3.4, 7.2)
2. We are invoking constructor from API
Charge(double x0, double y0, double q0)
*/
Charge c1 = new Charge(.51, .63, 21.3);
Charge c2 = new Charge(.13, .94, 81.9);
// print out charge so we know what we are dealing with
System.out.println(c1);
System.out.println(c2);
/*
Here we create variables to hold the return from our potential method
which is enacted on our c1 and c2 objects.
1. We call a method on an object by:
objectName.methodName(appropriate parameters)
*/
double v1 = c1.potentialAt(x, y);
double v2 = c2.potentialAt(x, y);
// Concatenate results and print them out.
System.out.println(v1 + v2);
System.out.println("This is the printf statement:");
System.out.printf("%.2E\n", v1 + v2);
}
}
Related
I'm learning Java on Codecademy and recently completed a project that calculates monthly payments for a car loan. The problem is that I don't understand the solution, and no one has responded to my question about it on the Codecademy forum.
Why are the instance variables created in the main method scope instead of just after the class has been declared? We haven’t seen any examples of this prior to this project and I don’t understand.
Here is the code:
//Calculates monthly car payment
public class CarLoan {
//Why aren't the variables created here rather than in the main method?
public static void main(String[] args) {
int carLoan = 10000;
int loanLength = 3;
int interestRate = 5;
int downPayment = 2000;
if (loanLength <=0 || interestRate <=0) {
System.out.println("Error! You must take out a valid car loan.");
} else if (downPayment >= carLoan) {
System.out.println("The car can be paid in full.");
} else {
int remainingBalance = carLoan - downPayment;
int months = loanLength * 12;
int monthlyBalance = remainingBalance / months;
int interest = (monthlyBalance * interestRate) / 100;
int monthlyPayment = monthlyBalance + interest;
System.out.println(monthlyPayment);
}
}
}
Variables defined within a method are local variables, they belong to an invocation of the method, not to an instance of an object.
The intent seems to be to provide an example that is understandable to beginners who haven't been introduced to constructors, instance variables, and methods. They want to teach local variable declaration, some simple calculating and if-statements, and printing to the console before getting into that other stuff.
As an exercise it would be fine for you to change the CarLoan class to give it instance variables, just to see another way to do it. Keep the variable values hard-coded, make an instance method that calculates the monthly payment, and have the main method print the result to the console.
This code does not run when I try to compile it, I am sure it is because I
defined my function/method incorrectly, so it would be much appreciated if
someone can correct my code and also tell me what is wrong with it.
I know C++ so I tried to define the function like how I would define it
normally in Cpp but with a few tweaks. I really don't know what I am doing
right now.
class Calculator {
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
final float k = 5 / 9;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
public float Converter(float Farenheit) {
return 5 / 9 * (Farenheit - 32);
}
}
}
So the comments noted the key issues. The method cannot be within main. 5/9=0 in Java. Here is a little program I just checked on jdoodle.com. It does what you said in what might be typical Java style (though for sure there are possible improvements and things with which to quibble). For learning Java (which is not the same as for experienced users for development), bluej is an interesting IDE with which to start (specifically because it doesn't do all the work for you). But StackOverflow does not want judgment questions like that, so ignore if you wish.
public class Calculator {
public double converter(double Farenheit) {// convention converter lower case because not a class name
return 5.0 / 9 * (Farenheit - 32); //note 5.0 ensures real number arithmetic, not integer
}
public static void main(String[] arguments) {
Calculator calculator = new Calculator();// make a calculator object, alternative would be to declare converter static
double Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
calculator.converter(Farenheit));
}
}
Your method public float Converter(float Farenheit) is written inside main method . This is not allowed in JAVA . You can however write a anonymous class inside a method and calls its methods .
The correct code is :
class Calculator {
private static final float k = 5.0f / 9;
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
}
public static float Converter(float Farenheit) {
return k * (Farenheit - 32);
}
}
Please note I have modified Converter method to a static one . We cannot call non static methods from static context in JAVA(as main is static here) . If Converter would have been non static then we would have to create an object of the Calculator class.
Calculator c = new Calculator();
c.Converter(Fahrenheit);
You can declare k as class level variable if it is to be used across multiple methods and has a constant value .
private static final float k = 5.0f / 9;
I am very new with Java and now read book Shield complete reference 9th edition.
I wrote the next code:
class Area {
double Area (double x, double y){
double z;
this.z = 5; // Problem 1
return z = x*y;
};
}
class ThisIsSparta {
public static void main (String args []){
double x = 10;
double y = 5;
double z = 0;
Area result = new Area (x,y); //Problem 2
z = result.Area(x, y);
System.out.println("Test " + z);
}
}
Problem 1: I could not understand purpose of "this", I thought that it is reference to object which had call class. So in my opinion I should return to main with z = 5. Instead i'am getting an error (compiler does not pass through it).
Problem 2: In a book example constructor was called with two arguments right during declaration, but in my case compiler do not allow to do it. Yes, I could do it in the next line, but I don't understand what is wrong.
Problem 1 :
this refers to the current object. In your case, it is an object of Area.
Read more:
What is the meaning of "this" in Java?
Problem 2:
You have not defined any constructor that takes two argument.
double Area (double x, double y) is not the right signature for a constructor as it contains return type as double.
Read more on this here : Why do constructors not return values?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm fairly new to java, so bear with me.
I'm using x and y variables inside a coordinate array.
Mutator:
public void setCoordinate (double _x, double _y) {
x = _x;
y = _y;
double [] coordinate = new double [2];
coordinate[0] = x;
coordinate[1] = y;
}
The part I'm having trouble with is the accessor:
public double[] getCoordinate() {
return "(" + coordinate[0] + ", " + coordinate[1] + ")";
}
I'm getting a "symbol: variable coordinate, location: class Address, error: cannot find symbol" error. Any idea as to why I'm getting this error? I wrote the other accessors the same way and I'm not having any trouble.
Also... how would I call each variable (x and y) separately in another method? a1.getCoordinate() returns both values (x, y), but I want to use x and y in an equation later on an I'm not 100% sure of how to do this.
Your first problem is due to the coordinate variable being declared inside of the setCoordinate(...) method, and thus it is visible only in this method and invisible everywhere else. In other words, its scope is limited to the method.
One solution to this problem is to make coordinate a class field, but if you do this, then you will want to get rid of the x and y class fields since they will be unnecessary duplicate variables and can lead to confusion if x and y somehow get out of sync with coordinate. i.e.,
private double[] coordinate;
public void setCoordinate(double x, double y) {
coordinate = new double[]{x, y}; // coordinate is a class field
}
public double[] getCoordinate() {
coordinate;
}
Alternatively you can keep x and y and simply create a double array object on the fly inside of the getCoordinate() method with your x and y variables as the need arises. i.e.,
private double x;
private double y;
public void setCoordinate(double x, double y) {
this.x = x; // x is a class field
this.y = y; // y is a class field
}
public double[] getCoordinate() {
return new double[] {x, y};
}
Your second problem is that the getCoordinate() methods declares that it will return a double array:
public double[] getCoordinate() {
but you're trying to return a String:
return "(" + coordinate[0] + ", " + coordinate[1] + ")";
You don't want to do this since it "breaks the method's contract", since you're not returning the type you've promised to return. Instead return the type that the method has been declared to return (or a child type of the declared type since return types allow for "covariance" -- but this is not applicable in your situation).
double [] coordinate = new double [2];
should be declared outside the mutator as its scope is only for that mutator.
You should have something as follows:
class SomeClass{
double [] coordinate = new double [2];
int x, y;
public double[] getCoordinate;
//methods
}
You're defining coordinate in the scope of the setCoordinate function. You'll need to define coordinate at the class level in order to access it in both methods.
This question already has answers here:
When to use nested class?
(3 answers)
Closed 9 years ago.
If a function returns 2 values, for example: min/max in array or for example, x and y axis of a point, it would need to create an object, since a function cannot return 2 values.
Now, consider a client whose 'only' function is to use getters in the returned object and print.
AND
The returned object say MinMax or Point object is created only by one class,
Should we use a nested class (eg: MinMax, Point can be nested class) or use a top level class?
This is a generic question - below is just one such example related to the question. Please done answer related to the code sample as it is a very generic question not bound to the sample code.
Should the Point class be inner class returned similar to the way itr is returned by arraylist ?
class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
public class IntersectionOf2Lines {
public static Point calculateIntersection(Line line1, Line line2) {
int x = (line2.getConstant() - line1.getConstant()) / (line1.getSlope() - line2.getSlope());
int y = line1.getSlope() * x + line1.getConstant();
return new Point(x, y);
}
Line line3 = new Line(2, 2);
Line line4 = new Line(3, 2);
Point p1 = IntersectionOf2Lines.calculateIntersection(line3, line4);
System.out.println("Expected: x = 0, Actual x = " + p1.getX() + " Expected y=2, Actual y = " + p1.getY());
IMHO it is a matter of style. I would look at it from the point of view of someone who is reading your code from the first time. Which classes do you want to make obvious and which ones do you want to group away and they only need to read when they get into the details.
BTW: A nested class need to be nested inside the scope of another class, not just in the same class file as it is in your example.