Creating objects in Java - java

I have the following class:
class Position {
private double x,y;
private int id;
private static int count=0; //counts number of times a Position object has been created
public Position (double initX, double initY) {
x=initX;
y=initY;
id=count;
count++;
}
public Position (Position a) {
id=count;
count++;
x=a.x;
y=a.y;
}
I want to now create a Position object in another of my .java files. How would I do so? Wouldnt I just use Position x=new Position; ? Thats not working. Do I have to import the position class into the files? I tried that too, didnt work. Wouldnt let me import. My files are in the default folder.
Here's where I want to use it. Im not even sure Im reading the instructions correctly. Is this what they want from me? To initialize every element of the array to a new position object?
/**
* Returns an array of num positions. Each position is initialized to a random
* (x,y) position.
* if num is less than zero, just return an empty array of length 0.
*
* #param num
* number of positions to create
* #return array of newly minted Points
*/
public int[] randomPos(int[] a) {
int numPositions=Position.getNumPositionsCreated();
int[] posArr=new int[numPositions];
int x,y;
for (int i=0; i<numPositions;i++)
Position rand = new Position(x,y);
//

You would need to invoke the constructor,
Position x = new Position(2.0,2.0);
Since one of your constructor takes two double's as arguments, I used those as an example.
Or, you could create a new Position object by passing in another Position object,
Position otherX = new Position(new Position(2.0,2.0));
// or combining our above example assuming that x is already instantiated
Position otherX = new Position(x);
Also, just in case you are unsure, there is a difference between instantiation and declaration!
Instantiation:
Position posX = new Position(1.0, 4.0);
Now, posX is an instance of a Position object, because we construct our object by invoking the constructor.
Declaration:
Position posX;
Note that the posX variable is declared to be a Position object, but has not yet been instantiated so posX would have a null reference.
Update:
Without actually do the homework for you, because you will not learn that way. I can tell you that what you have so far, and what is listed in the javadoc above do not agree. Also, given by the way the javadoc is written, it is tough to follow, therefore let me try to clean it up for you and leave you to do the rest,
/* Returns an array of n Positions. Each Position is initialized to a random
* (x,y) position.
* if n is less than zero, just return an empty array of length 0.
*
* #param n
* number of Positions to create
* #return array of newly created Positions
*/
Now we can break down that javadoc, so lets pinpoint what we know.
We are passing an argument, n which indicates how big the Positions array should be.
We need to check to see if n is equal to 0, if so we return an empty Position array.
Each Position object would be instantiated with random x and y values.
We know that we need to return an Position array.
This should get you started, I am sure you can figure out the rest.

Position x = new Position(1.0, 2.0);
For example. The way you have it now is missing method arguments.

Position x = new Position(1d,2d);
You need to pass your constructor arguments. Since you defined 2 constructors on your Position class, you must use one of them. Usually not a bad idea to put a do nothing constructor on your class. like
Postion () {}
or in your case
Position () {
Position.static++;
}
since you are counting. Note you should reference static members statically.

Your constructors take arguments, so you have to provide some.
Position p = new Position(1.0, -2.0);
If you want to create one without arguments, you need to a add a zero-argument constructor.
public Position() {
}
which would then be invoked by doing Position p = new Position() (the parenthesis are required when not passing in arguments)
If you don't define any constructors, java automatically creates an implied zero-arg constructor, but once you define a different constructor, you have to explicitly define a zero-arg constructor to have one.
If both of your classes are in the default package you shouldn't need to import anything.

Java already has a Point class. It may be overkill for you but though I'd mention it.
http://download-llnw.oracle.com/javase/6/docs/api/java/awt/geom/Point2D.html

Don't forget the parentheses and arguments to pass into the constructor when you call new, eg:
Position p = new Position(x, y);
Depending upon where the other class is, you may also need to make Position a public class (it appears you are using the default visibility of package-private).
Also note that x and y must be initialized first,

Related

how to take onlythe x and y from Point class

I have a variable private Point _centralStation which located in class that I called her City.
the user in the main class decides which value will be to the location of the centralStation.
So he put for example:
Point center = new Point(5,5) .
I want to create a method who called MoveCentralStation(int x, int y)
that moves the location from his last value to the new one, but
the new points have to be in the first quarter of the x,y axis.
I mean x cannot be -4 for example.
let's say for the exmaple it was 5,5
and now the user entered -4,5
how can I deal with the x and y new values sepertely?
Thank you
You have to explain yourself a little better. However, this is what I understood.
You have such a class:
class City{
private Point _centralStation;
public City(){
this._centralStation = new Point(5,5);
//the initialization you specified
}
public void moveCentralStation(int new_x, int new_y){
//TODO exactly what you have to implement
}
public Point getCentralStation(){
//since you are not implementing just getters and setters you rather do
return new Point(_centralStation.x,_centralStation.y);
//instead of return _centralStation [this is what we call defensive copies]
}
}
Well, somewhere in the code, a client would call
City c = new City();
c.moveCentralStation(x,y); //given x,y are variables in the client's context
And these are the requirements for the moveCentralStation(int x, int y) operation:
x coordinate shall be positive
y coordinate shall be positive
First of all I suggest you to follow style conventions on the way you code: use capital letters only for the class names. Let's jump into the real problem.
We need to refine the above requirements to make a specific implementation compliant with them. They aren't clear enough. An example of refinining i may suggest is the following:
If x coordinate is less than zero, an IllegalArgumentException shall be thrown
If y coordinate is less than zero, an IllegalArgumentException shall be thrown
And that's very simple to implement:
public void moveCentralStation(int new_x, int new_y){
if(new_x < 0) throw new IllegalArgumentException("x must be positive");
if(new_y < 0) throw new IllegalArgumentException("y must be positive");
_centralStation.x = new_x;
_centralStation.y = new_y;
}
It's a good practice to set private fields only when they are all consistants.

Class Random only Generates 0

Okay
I have The problem that i want to generate 64 numbers between 0 and 1 (that means 0 or 1)
the function i have currently is:
public static int randNr(int max) {
Random r = new Random();
int o = r.nextInt(max);
return o;
}
But it always returns 0.
Is there any way to make that it generates also a 1 ?
EDIT:
the function is located in a different java file than when i calling it!
Two issues:
1) nextInt(max); generates a number from 0 and up to but not including max. My guess is that you're passing 1 as max. Pass 2 and all will be well.
2) Creating a new generator object each time ruins the statistical properties of the generator. You should create one Random instance and (i) either pass into the function or (ii) have the instance stored as a member variable.
This function works fine. You are probably calling it with the wrong arguments. It should be:
randNr(2)
Why? Because it's using the Random#nextInt(max) method, which will return a random integer in the range [0, max-1] (including 0 and max-1).
Note: It's not recommended to create a new Random object each time you call the function. One solution would be to declare the Random object as an static member of the class:
public class Test
{
private static Random r = new Random();
// ...
}
Another solution would be to use the static method Math.random()1:
int o = (int) Math.round(Math.random());
1: Could someone confirm if this method is faster than the OP's one?

How to breakdown a method and process it [closed]

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
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.

Random number generator method for linked list assignment

So, I have to make a random number generator to get numbers ranging from 0 to 400. I'm putting these into an array and then sorting them later on. I just am not sure how to go about doing this. I was given something along the lines of;
public int nextInt(400) //gives me errors
{
random.setSeed(12345L);
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
}
I've already called the random class, since the directions indicated that. I just don't know why this is not working. It's giving me errors especially with the first part; class, interface, or enum expected. Could somebody steer me in the right direction please?
Functions in Java (all programming languages) have "variables" in their definition.
You've got:
public int nextInt(400)
Over here, you want your 400 to be a value that is passed to the function.
Think of this as math. I'm sure you've dealt with something like f(x) = 2 * x. Here, x is the variable, and you "evaluate" f(x) with a value for x. Similarly, in programming, we'd have something like :
public int nextInt(int x)
As you see, our function defines x to be of type int. This is necessary in a language like Java because you're telling the compiler that this function will only accept integers for x.
Now that you've done that, you can use x as a variable in the body of your function.
Note that whenever you use a variable, it first has to be defined. A line such as:
int variable;
defines variable as an int.
Your program is missing these for random, val, arr, and a. Note here that arr and a are arrays (and somehow I get the feeling that they should not be two separate variables).
You should really brush up on variables definitions, arrays, and functions before attempting this question. Your best resource would be your textbook, because it'll explain everything in an organized, step-by-step manner. You can also try the many tutorials that are available online. If you have specific questions, you can always come back to StackOverflow and I'm sure you'll find help here.
Good luck!
You need to define this function within a class definition
even you have specified :
public int nextInt(400)
in this line function returns int and in your whole body u didn't have any return statement.
and yes as Kshitij Mehata suggested dont use 400 directly as value use variable over there.
this should be your function:
public int[] nextInt(int x) //gives me errors
{
random.setSeed(12345L);
int[] a=new int[arr.size];
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
return a;
}
even there is some issue with arr from where this arr come?

"Cannot find symbol" - class with the main method can call methods from one of the other classes but not the second of the others?

I've been lurking here for a little while, but I've come into a problem that I can't solve in some Java programs I'm writing for an assignment. I bet they're not too difficult to figure out, but I'm just not getting it.
I've been getting errors along the lines of this:
RugbyTeamLadderEditor.java:125: cannot find symbol
symbol : method findAveragePoints(java.util.ArrayList<RugbyTeam>)
location: class RugbyTeamLadderEditor
double averagePointsToBePrinted = findAveragePoints(rugbyTeams);
I have three classes, and, from the class with the main method (RugbyTeamLadderEditor), I can call the constructor class, but not the other class which has some methods in it (Part1). Should I be doing something with packages? - all I know is that I didn't learn anything about packages in this introductory programming course that I'm doing, and I'm not sure how they would be received if I were to use them.
My code is a couple of hundred lines long, so I put them in pastebin - I hope I haven't transgressed any faux pas by doing this :/ Every class is in its own .java file.
http://pastebin.com/FrjYhR2f
Cheers!
EDIT: a few fragments of my code:
In RugbyTeamLadderEditor.java:
// if the identification number is equal to 5, then print out the average points of all of the teams in the ArrayList
else if (identificationNumber == 5)
{
double averagePointsToBePrinted = findAveragePoints(rugbyTeams);
}
In Part1.java:
/**
* This method takes a RugbyTeam ArrayList and returns a
* double that represents the average of the points of all
* of the rugby teams
*/
public static double findAveragePoints(ArrayList<RugbyTeam> rugbyTeams)
{
// If there are no objects in the ArrayList rugbyTeams, return 0
if (rugbyTeams.size() == 0)
return 0;
// Declare a variable that represents the addition of the points of each team;
// initialise it to 0
double totalPoints = 0;
// This is a code-cliche for traversing an ArrayList
for (int i = 0; i < rugbyTeams.size(); i++)
{
// Find then number of points a team has and add that number to totalPoints
RugbyTeam r = rugbyTeams.get(i);
totalPoints = totalPoints + r.getPoints();
}
// Declare a variable that represents the average of the points of each teams,
// i.e. the addition of the points of each team divided by the number of teams
// (i.e. the number of elements in the ArrayList); initialise it to 0
double averagePoints = totalPoints / rugbyTeams.size();
return averagePoints;
}
It's not quite finished yet - I still need to put a print statement in to print that double, but it's irrelevant for now because I can't actually get that double to take on a value.
Your are trying to call the method findAveragePoints. With the current implementation you say, that the method will be found in the class RugbyTeamLadderEditor. But the method is defined in the class Part1. So to make this work you prepend the call to the method with Part1. (since it is a static method) and the program should work.
EDIT
The code would basically look like this
double averagePointsToBePrinted = Part1.findAveragePoints(rugbyTeams);
Also every time you try to call a method that is defined in another class than the current you either have to provide an instance of this class or prepend the name of the class (like here Part1) to the method called.
As a side node you should change the name of your variable quitProgram. The name of the variable and its meaning contradict each other. So to make things more clear for anyone reading the code you should change either the name or the handling.

Categories