Accessing objects from another class in java? - java

i know that this question has been asked many types, but i am not getting trough the problem. So following. I have created a class that is creating array of 2 positions. The goal is to create point coordinates so i can generate several points later. Hier is my code
import java.util.Random;
public class Coor {
private static int[] coord;
public static int[] generate(){
coord = new int[2];
return coord;
}
public static void printX(){
System.out.println("X = " + coord[0] );
}
public static void printY(){
System.out.println("Y = " + coord[1] );
}
public static int randomFill(){
Random rand = new Random();
int randomNum = rand.nextInt(99);
return randomNum;
}
public static void main(String args[]) {
generate();
for(int i = 0; i < 2; i++){
coord[i] = randomFill();
}
printX();
printY();
}
}
So, this is working perfect, but what I want is to create the points in another class and to use them there, but I have no idea how to achieve this. I am new to java, and I have almost understood some examples in the oracle docs, but can not implement it. Can you please help me a little? I just need one example class which is obtaining the coordinates of the points, after that I can extend it alone for my needs.

You should not make your data static and you should provide a public constructor see below.
public class Coord {
private int[] coord;
public Coord(int x, int y) {
coord = new int[2];
coord[0] = x;
coord[1] = y;
}
public void printX(){
System.out.println("X = " + coord[0] );
}
public void printY(){
System.out.println("Y = " + coord[1] );
}
public static void main(String[] args) {
Coord c1 = new Coord(10, 11);
Coord c2 = new Coord(23, 14);
}
}

Related

Java pass by reference int [duplicate]

This question already has answers here:
How do I pass a primitive data type by reference?
(8 answers)
Closed 7 years ago.
here is my code
public class Scale {
public static void main(String[] args) {
int x = 4;
int y = 3;
int faktor = 2;
skaliere(x,y,faktor);
System.out.println(x + " " + y);
}
public static void skaliere(int x, int y, int faktor){
// ?
}
}
I want to change the scale the x and y by faktor, not using a return value. Just by the skaliere method.
I want to change the scale the x and y by faktor, not using a return value. Just by the skaliere method.
Note that Java is not pass by reference, it's always pass by value.
Without any hack, simply you can't because they are primitives. If they are mutable objects, yes you can change their state.
That hack would be making them static and assigning values inside that method.
You can always make your own MutableInteger class
class MutableInteger{
private int value;
public MutableInteger(int v){
this.value = v;
}
public int get(){
return value;
}
public void set(int newValue){
this.value = newValue;
}
#Override
public String toString() {
return Integer.toString(value);
}
}
Then use it in your code:
public static void main(String[] args) {
MutableInteger x = new MutableInteger(4);
MutableInteger y = new MutableInteger(3);
int faktor = 2;
skaliere(x,y,faktor);
System.out.println(x + " " + y);
}
public static void skaliere(MutableInteger x, MutableInteger y, int faktor){
x.set(x.get() *faktor);
y.set(x.get() *faktor);
}
Since you are making your own class, you can even move the skaliere method into your MutableInteger
class MutableInteger{
...
public void skaliere(int faktor){
this.value *=faktor;
}
}
which makes your code look like this:
public static void skaliere(MutableInteger x, MutableInteger y, int faktor){
x.skaliere(faktor);
y.skaliere(faktor);
}
You don't even need the static method anymore
You could do this with an object that wraps the two values. This is because the object reference is passed to the method. If you pass a primitive which are immutable, they will never be changed on the return, it would only change a copy in the method. Using an object, you can pass the containing values and it would be the ones referenced by the main method when retrieved.
public static void main(String[] args) {
// org.eclipse.swt.graphics.Point
Point p = new Point(0, 0);
p.x = 4;
p.y = 3;
int faktor = 2;
skaliere(p,faktor);
System.out.println(p.x + " " + p.y);
}
public static void skaliere(Point p, int factor){
p.x *= factor;
p.y *= factor;
}

"new way for loop" in Java, not working, suggestion?

this is my problem:
I was trying to use the new for loop in java to print out some strings with doubles. When i compile the code, no errors, but no output, it's like if the for loop isn't working, any help?
the loop it's right in the end, i've printed all the code just to be sure.
abstract class Figure3D {
private float[] center;
protected void setCenter(float[] center){this.center = center;}
public abstract double calcolateVolumn();
protected abstract String figureType();
public void printVolumn(){
System.out.println("Volumn "+ figureType() + calcolateVolumn());
}
}
class Cube extends Figure3D{
private float side;
public Cube(float side, float[] center){
this.side = side;
setCenter(center);
}
#Override
protected String figureType(){
return "Cube ";
}
#Override
public double calcolateVolumn(){
return side*side*side;
}
}
class Sphere extends Figure3D {
private float radius;
public Sphere(float radius, float[] center){
this.radius = radius;
setCenter(center);
}
protected String figureType(){return "Sphere ";}
public double calcolateVolumn(){return ((4f/3f)*radius*radius*radius*3.14f);}
}
import java.util.ArrayList;
import java.util.List;
class TridimensionalFigures {
public static void main(String[] args) {
List<Figure3D> figures3d = new ArrayList<>(10);
Sphere sphere;
Cube cube;
for (int i = 0; i < figures3d.size(); i++) {
sphere = new Sphere(i, new float[] {i, i, i});
figures3d.add(i, sphere);
i++;
cube = new Cube(i, new float[] {i, i, i});
}
//TOFIX: it needs to print out the volums of all the objects in the arraylist
for (Figure3D figures : figures3d) {
System.out.printf("The volumns is: %s %n", figures.calcolateVolumn());
}
}
}
figures3d.size() is 0, so you are not adding anything to the list.
Try changing
for (int i = 0; i < figures3d.size(); i++) {
to
for (int i = 0; i < 10; i++) {
The problem is, the list is never actually populated.
You set it's initial capacity using the constructor, but that doesn't change the size; it just prevents reallocations later.
Because the size is 0, the populizing loop never runs, so the second loop (in question) is skipped due to the list being empty.
Instead of using the list's size to control the populating loop, extract the magic 10 into its own variable, and loop while i < tenVariable.

Aid with quick sort algorithm in java (netbeans)

I am quite new to programming and I am just starting using java. My task was to write a program using quick sort, I managed to write it but it always gives me an index out of bounds. Could anyone take a look at my code and help me by identifying what I am doing wrong? Thanks
This is the code for the main class.
package quicksort;
public class Quicksort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] x = {5,3,10,1,9,8,7,4,2,6,0};
quicksort_class q = new quicksort_class(x);
q.sort();
for(int i = 0; i < 11-1; i++)
{
System.out.println(x[i]);
}
}
}
This is the code for quicksort_class.
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
public void partitionstep(int leftlimit, int rightlimit)
{
int LPointer = leftlimit;
int RPointer = rightlimit;
Random random = new Random();
int midpoint = random.nextInt(11);
int checknumber = array1[midpoint];
while(LPointer < RPointer)
{
while(array1[LPointer] <= checknumber)
{
LPointer = LPointer + 1;
}
while(array1[RPointer] >= checknumber)
{
RPointer = RPointer --;
}
swap(LPointer, RPointer);
partitionstep(leftlimit, midpoint - 1);
partitionstep(midpoint + 1, rightlimit);
}
}
public void swap(int x, int y)
{
int temp = array1[x];
array1[x] = array1[y];
array1[y] = temp;
}
public void sort()
{
partitionstep(0, array1.length - 1);
}
}
Your midpoint value should be calculated based on your leftLimit and rightLimit. It should not be a random value based off of the fixed value 11.

In Object Array = all elements are same... After assign data

For Example if I Create array of object
And assing data...
short version of problem.
array[0].init("ce", 2)
array[1].init("nh", 2)
Output... Of array[0]
Will be same as array[1]
But why? what's wrong? I need.. not same results
Here is code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.lang.Math;
public class Gra_ulamki {
/**
* #param args the command line arguments
*/
public static ulamek[] tab_ulamkow;
public static void main(String[] args)
{
tab_ulamkow = new ulamek[30];
tab_ulamkow[0] = new ulamek();
tab_ulamkow[0].init("dd", 5);
tab_ulamkow[1] = new ulamek();
tab_ulamkow[1].init("dde", 8);
System.out.println("poz x --" + tab_ulamkow[0].x + "-- y poz " + tab_ulamkow[0].y);
System.out.println("poz x --" + tab_ulamkow[1].x + "-- y poz " + tab_ulamkow[1].y);
// TODO code application logic here
//new GUI();
//new GUI();
}
}
class ulamek
{
public static String ch_v;
public static int x = 0, y = -5, y_max = 325;
public void init(String a, int number)
{
this.ch_v = a;
// przypisanie x
this.x = number;
}
public void move()
{
// restart pozycji w osi y
if(this.y < y_max)
{
this.y += +1;
}
else
{
this.y = -5;
}
}
}
Thank You for help
If a data member is static, this means that it is shared by all instances of the class:
public static String ch_v;
public static int x = 0, y = -5, y_max = 325;
Remove the two static modifiers.
The fields in your ulamek class are static's
It means that they belong to the ulamek Type, and not it's instances (objects).
Alter it this way:
class ulamek
{
public String ch_v;
public int x = 0, y = -5, y_max = 325;
...
And it should work.
In class ulamek:
Change:
public static String ch_v;
public static int x = 0, y = -5, y_max = 325;
to:
public String ch_v;
public int x = 0, y = -5, y_max = 325;
Declaring a variable or method static means that its value is available across all classes.

Java how to sort an ArrayList of Point objects

I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X.
I read online to make a new class PointCompare that implements Comparator, however I'm not sure how this works and therefore I have a compiler error in the sortByXCoordinates method.
Help would be appreciated a lot, and any comments are welcome, thanks in advance.
Here is some of my code:
import javax.swing.JOptionPane;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//import java.util.Iterator;
public class ConvexHullMain {
private Point coordinates = new Point(0, 0);
private final int MAX_POINTS = 3;
private ArrayList<Point> coordinateList = new ArrayList<Point>();
public void inputCoordinates() {
String tempString; // temp string for JOptionPane
int tempx = 0;
int tempy = 0;
for (int i = 0; i < MAX_POINTS; i++) {
try {
// input x coordinates
tempString = JOptionPane.showInputDialog(null,
"Enter X coordinate:");
tempx = Integer.parseInt(tempString);
// input y coordinates
tempString = JOptionPane.showInputDialog(null,
"Enter Y coordinate:");
tempy = Integer.parseInt(tempString);
coordinates.setLocation(tempx, tempy);// set input data into
// coordinates object
coordinateList.add(coordinates.getLocation()); // put in
// arrayList
} // end Try
catch (NumberFormatException e) {
System.err.println("ERROR!");
main(null);
} // end catch
}// end for loop
}
public void displayPoints() {
for (int i = 0; i < MAX_POINTS; i++) {
JOptionPane.showMessageDialog(null, "Point number " + (i + 1)
+ " is: " + coordinateList.get(i));
}
// alt method
// Iterator i = coordinateList.iterator();
// String outputTemp;
// while (i.hasNext()) {
// outputTemp = i.next().toString();
// JOptionPane.showMessageDialog(null, "Point number " + " is: "
// + outputTemp);
// }
}
/**
* This sorts the points by the X coordinates
*/
public void sortByXCoordinates(){
coordinateList.sort(coordinates, new PointCompare());
}
public class PointCompare implements Comparator<Point> {
public int compare(Point a, Point b) {
if (a.x < b.x) {
return -1;
} else if (a.x > b.x) {
return 1;
} else {
return 0;
}
}
}
public static void main(String[] args) {
ConvexHullMain main = new ConvexHullMain();
main.inputCoordinates();
main.displayPoints();
}
}
private ArrayList<Point> coordinateList = new ArrayList<Point>();
...
Collections.sort(coordinateList, new PointCompare());
...
public class PointCompare implements Comparator<Point> {
public int compare(Point a, Point b) {
if (a.x < b.x) {
return -1;
}
else if (a.x > b.x) {
return 1;
}
else {
return 0;
}
}
}
You were close. The problem you had was simply that you invoked
public void sortByXCoordinates(){
coordinateList.sort(coordinates, new PointCompare());
}
What you want is this:
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.JOptionPane;
public class MainClass {
private final Point coordinates = new Point(0, 0);
private final int MAX_POINTS = 3;
private final ArrayList<Point> coordinateList = new ArrayList<Point>();
public void inputCoordinates() {
String tempString;
int tempx = 0;
int tempy = 0;
for (int i = 0; i < this.MAX_POINTS; i++) {
try {
tempString = JOptionPane.showInputDialog(null, "Enter X coordinate:");
tempx = Integer.parseInt(tempString);
tempString = JOptionPane.showInputDialog(null, "Enter Y coordinate:");
tempy = Integer.parseInt(tempString);
this.coordinates.setLocation(tempx, tempy);// set input data into
this.coordinateList.add(this.coordinates.getLocation()); // put in
}
catch (final NumberFormatException e) {
System.err.println("ERROR!");
main(null);
}
}
}
public void displayPoints() {
for (int i = 0; i < this.MAX_POINTS; i++) {
JOptionPane.showMessageDialog(null, "Point number " + (i + 1) + " is: " + this.coordinateList.get(i));
}
}
/**
* This sorts the points by the X coordinates
*/
public void sortByXCoordinates() {
Collections.sort(this.coordinateList, new PointCompare());
}
public class PointCompare
implements Comparator<Point> {
public int compare(final Point a, final Point b) {
if (a.x < b.x) {
return -1;
}
else if (a.x > b.x) {
return 1;
}
else {
return 0;
}
}
}
public static void main(final String[] args) {
final MainClass main = new MainClass();
main.inputCoordinates();
main.displayPoints();
}
}
i'm going to ignore all of the code you posted because you've just dumped everything without taking the time to identify the relevant areas.
now, from your question: you have an ArrayList containing Points. You want to sort it by the X axis/value.
List<Point> list = new ArrayList<Point>();
Firstly you need a Comparator which will compare one Point to another.
Comparator<Point> comp = new Comparator<Point>()
{
#Override
public int compare(Point o1, Point o2)
{
return new Integer(o1.x).compareTo(o2.x);
}
};
I choose to "box" the int to an Integer and use Integer's compareTo method. You could come up with a tidier method of comparison, up to you.
Then you can use the utility method Collections.sort
Collections.sort(list, comp);
and your list is sorted.
I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X
You can use a Bean Comparator or a custom Comparator as described in the blog.
The ArrayList class (see API documentation: http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html) that you use for your 'coordinateList' does not have a sort() method. You will have to implement this yourself, or use Collections.sort().

Categories

Resources