Using an object in another object java - java

So I'm setting a node class that shows links between one node and another to find the shortest route. I decided to use a seperate object class to store the links between node A and B to avoid using two-dimensional arrays.
After saving the project in eclipse, just as a checkpoint so I don't lose my data, all of a sudden red lines appeared under any calls of DistanceBetween, saying that the method doesn't exist in that object class, although it does, as you'll see.
Note: Any bolded part is throwing an error, in Node. Generally it states that the method doesn't exist in DistanceBetween, or that the constructor (int, int) is wrong, when it is not.
Should I use extend, a package?
public class DistanceBetween{
private int thisAddress;
private int distanceBetween;
public DistanceBetween(int myAddress, int myDistance){
thisAddress = myAddress;
myDistance = distanceBetween;
}
public int getAddress(){
return thisAddress;
}
public void setAddress(int newAddress){
thisAddress = newAddress;
}
public int getDistance(){
return distanceBetween;
}
public void setDistance(int newDistance){
distanceBetween = newDistance;
}
}
public class Node{
private int address;
private int distance;
private Node[] connectedNodes;
private DistanceBetween[] distances;
private boolean intersection;
public Node(int myAddress, Node[] myConnected, DistanceBetween[]
myDistances, boolean isIntersection){
address = myAddress;
connectedNodes = myConnected;
distances = myDistances;
intersection = isIntersection;
}
public int getThisAddress(){
return address;
}
public void setThisAddress(int newAddress){
address = newAddress;
}
public Node[] getConnected(){
return connectedNodes;
}
public void connectTwo(Node a, Node b){
for(int x = 0; x < a.getConnected().length; x++){
if(a.getConnected()[x].getThisAddress() == 0){
}
}
}
public DistanceBetween[] getDistances(){
return distances;
}
public void setDistances(DistanceBetween[] newDistances){
distances = newDistances;
}
public void addLink(Node a, Node b, int thisDistance){
DistanceBetween[] holderDistanceA = a.getDistances();
DistanceBetween[] holderDistanceB = a.getDistances();
int flags = 0;
for(int x = 0; x < holderDistanceA.length; x++){
if(holderDistanceA[x].**getAddress()** == 0){
DistanceBetween aAndB = new **DistanceBetween(b.getThisAddress(),thisDistance);**
holderDistanceA[x] = aAndB;
flags++;
break;
}
}
for(int x = 0; x < holderDistanceB.length; x++){
if(holderDistanceB[x].**getAddress()** == 0){
DistanceBetween bAndA = new **DistanceBetween(a.getThisAddress(),thisDistance);**
holderDistanceB[x] = bAndA;
break;
}
}
if(flags < 1){
System.out.println("Error, cannot add a link, link load is full.");
}
a.setDistances(holderDistanceA);
b.setDistances(holderDistanceB);
}
public int getDistanceBetween(Node a, Node b){
int result = 0;
for(int x = 0; x < a.getDistances().length; x++){
if(a.getDistances()[x].**getAddress()** == b.getThisAddress()){
result = a.getDistances()[x].**getDistance()**;
}
}
return result;
}
public boolean equals(Node a, Node b){
if(a.address == b.address){
return true;
}else
return false;
}
}

Your code compiles fine, it would appear that you have the 2 classes in different packages. To fix you can:
put the 2 classes into the same package
import the DistanceBetween package into the Node class.
import yourpackagename.DistanceBetween;

Make sure you do not have a class named DistanceBetween somewhere else in your project, or, in case you do, that you're importing the right one where the DistanceBetween code you posted is intended to be used.
The Open Type tool in Eclipse (Ctrl + Shift + T) allows you to search for the location of classes along your workspace.

Related

Java Data-structures hashtable

How can I solve this error (the error is in bold):
What I need to do is hash the elements when I copy them to the temp array
public class LinearProbingHashTable<E> {
private Entry[] hashArray;
private Entry defunct;
public LinearProbingHashTable(int size) {
hashArray = new Entry[size];
defunct = new Entry(-1, null);
}
public int hashFunc(int key) {
return key % hashArray.length;
}
private void expand(int newCapacity) {
Entry<E> temp[];
temp = new Entry[newCapacity];
// add you code here
for( int i=0; i< hashArray.length; i++) {
int index = **hashFunc**(hashArray[i]);
while(**temp[index]!=0**) {
index = (index+1)% temp.length;
}
temp[index]=hashArray[i];
}
hashArray = temp;
}
// INCLUDED FOR TESTING
public int getCapacity() {
return hashArray.length;
}
public class Entry<E> {
private int key;
private E data;
public Entry(int k, E d) {
key = k;
data = d;
}
public int getKey() {
return key;
}
public E getData() {
return data;
}
public void display() {
System.out.print(key + ":");
System.out.println(data);
}
}
}
I need to fix the bold error but I couldn't.
The error I get is: The method hashFunc(int) in the type LinearProbingHashTable is not applicable for the arguments (LinearProbingHashTable.Entry)
And the error for the second line is: Incompatible operand types LinearProbingHashTable.Entry and int
The errors you are getting are because you are passing an Entry object into a method that expects an int, and because you try to compare an Entry object with an int.
Your class Entry and the objects of it are not int objects and can't be used like one. But your class has an int field private int key that I would guess you probably meant to use in both cases.
So you need to change your code to use that field by using the getter of your class:
change
int index = hashFunc(hashArray[i]);
to
int index = hashFunc(hashArray[i].getKey());
and change
while(temp[index]!=0)
to
while(temp[index].getKey() != 0)
That will make your code syntactically correct. I can't say anything about whether it will be logically correct as I haven't tested that aspect.

How do I get a directory to "point" towards the right bucket when making my own extendable hashing project?

I've read up on the wiki page on creating a extendable hashtable Extendable Hashing. And now i'm trying to implement that into a program to better understand it but I can't figure out how to actually point the directories towards the buckets.
Directory class:
int GlobalDepth = 1;
int directories[];
public Directory() {
int temp = (int)Math.pow(2, GlobalDepth);
loadDirectories(temp);
}
public void loadDirectories(int n) {
for (int i = 0; i < n; i ++) {
String BinaryKey = Integer.toBinaryString(i);
String tempKey = BinaryKey.substring(0, this.GlobalDepth); // LSB
int depthKey = Integer.parseUnsignedInt(tempKey);
this.directories[i] = depthKey;
}
}
public void increaseGlobalDepth() {
this.GlobalDepth ++;
loadDirectories((int)(Math.pow(2, this.GlobalDepth))); // This method might throw an error because i think im changing the array size illegally and should instead create a temp array and copy/equal that array to this.directories
}
Bucket class:
private SomeObject[] item; // Class I'm using to hold all the information of something
private int Key, MaxBucketsize, LocalDepth = 1;
//Bucket next;
public Bucket() {
}
public Bucket(int BucketSize) {
this.item = new SomeObject[BucketSize]; // Initalises the number of items held in the bucket
this.MaxBucketsize = BucketSize; // Stores the max number of items that can be held in the bucket
}
public SomeObject[] getObjects() {
return this.item;
}
public boolean addObjects(int key, SomeObject item) {
boolean inserted = false;
for (int i = 0; i < this.MaxBucketsize; i ++) {
if (this.item[i] == null) { // only inserts if there is an empty spot in the bucket
this.item[i] = item;
this.item[i].setKey(key);
inserted = true;
break;
}
}
return inserted;
}
After doing all this, I'm not sure how to now link the 2 together like in the wiki page.

How to change the value of a String Array from a different class?

This may be a very simple question, but I can't seem to find a suitable answer on Google. I have a class called Player, which has a String array called playerInv with a size of 10.
In my Main Activity Class, I want to run a for loop to determine the first index in the array that is empty (""). I then want to populate that with a new string, and then terminate the loop. How do I do this?
Sorry for the nooby question. Like I said, I've tried Google to no avail!
For Loop:
String playerInvTemp[] = thePlayer.getPlayerInv; ERROR -- cannot resolve getPlayerInv
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i); ERROR cannot resolve setPlayerInv
//invText.setText();
Blood = true;
break;
}
}
Player Class:
public class Player {
private int playerPos;
private int playerHP;
private String playerInv[];
Player(int startPos, int startHP, String[] newInventory)
{
playerPos = startPos;
playerHP = startHP;
playerInv = newInventory;
}
public int getPlayerPos() {
return playerPos;
}
public void setPlayerPos(int playerPos) {
this.playerPos = playerPos;
}
public int getPlayerHP(){
return playerHP;
}
public void setPlayerHP(int playerHP){
this.playerHP = playerHP;
}
public String getPlayerInv(int pos)
{
return playerInv[pos];
}
public void setPlayerInv(String playerInv[]) {
for (int i=0; i<10; i++)
{
this.playerInv[i] = playerInv[i];
}
}
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String getPlayerInv()
{
return this.playerInv; *//this gives error "Incompatible types. Required java.lang.string, found java.lang.string[]"*
}
}
Do this
Add these two method in Player class
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String[] getPlayerInv()
{
return this.playerInv;
}
then change your for loop like this
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if (!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i);
//invText.setText();
Blood = true;
break;
}
}
Bunch of problems here, .length() is not valid for an array, it should be .length.
`for (int i=0; i<thePlayer.getPlayerInv(i).length(); i++)`
You most likely mean null or at least need to check for it, here and you need [] not ():
if (thePlayer.getPlayerInv[i] == "" or theplayer.getPlayerInv[i] == null)
This is all wrong, and as a matter of fact you need to post your code and errors, you have many problems and should start with learning some basics about Java.
Try some beginners tutorials (https://www.google.com/search?q=java+tutorials&ie=utf-8&oe=utf-8). You have a lot of both syntax and logic errors.
Do you run an instance of constructor player()??
I did
Player a=new Player();
a.getPlayerInv(0)
and works fine.

how to make an object move around a 2d grid array on its own towards other objects in java

OK so I have recently got my program to the point where it is allmost working, however I cant seem to figure out how to make my bug object move.
I have a class called AWorld that is populated with instances of a class method Randfood (ints between 0 and 9) in randomly placed possitions within the grid. It is also passed and instance of my class ABug as an attribute that is placed into the grip according to user input. my problem is I wish to make it move towards the food objects (my ints between 0-9) and when its next to them to have its energy level increased accordingly. it needs to only move towards an object when its within a set distance from it. i.e. 3 spaces in any direction, else just move randomly. my issue is i cant seem to figure out how to do that with my current code setup.
AWorld Class:
package finalversion2;
import java.util.Arrays;
import java.util.Random;
public class AWorld {
int x[] = new int[10], y[] = new int[10];
int row = 25;
int column = 25;
char[][] map;
public static int RandFood(int min, int max) {
Random rand = new Random(); // Initializes the random function.
int RandNum = rand.nextInt((max - min) + 1) + min; //generates a random number within the max and min ranges
return RandNum; //returns the random number
}
//Constructor
//Sets up map array for the AWorld object
//uses a bug that is passed to it
public AWorld(ABug bug) {
ABug bug1 = bug;
map = new char[row][column];
for (int i = 0; i < row; i++) {
for (int x1 = 0; x1 < column; x1++) {
map[i][x1] = ' ';
}
}
for (int i = 0; i < column; i++) {
Random rand = new Random();
int x = rand.nextInt(row);
int y = rand.nextInt(column);
map[x][y] = (char) RandFood(48, 57);
map[bug1.getHPossistion()][bug1.getVPossistion()] = bug1.getSymbol(); // gets the bugs x and y possistion in the array (user defined) and puts it into the symbol variable
}
}
public void PrintWorld() {
for (int i = 0; i < row; i++) //these next two for loops print the array to the screen
{
System.out.print("|");
for (int x1 = 0; x1 < column; x1++) {
System.out.print(map[i][x1]);
}
System.out.println("|");
}
}
}
ABug:
package finalversion2;
public class ABug
{
public static void main(){
}
private String species = new String(); //instance variables (defines data of object)
private String name = new String();
private String description = new String();
private char symbol;
private int hPossistion, vPossistion, energy, iD;
public ABug(){
}
public ABug (String s, String n, String d, int h, int v, int e, int i){
this.species = s;
this.name = n;
this.description = d;
this.symbol = s.charAt(0);
this.hPossistion = h;
this.vPossistion = v;
this.energy = e;
this.iD = i;
}
//setters
public void setSpecies(String s){
this.species = s;
}
public void setName(String n){
this.name = n;
}
public void setSymbol(char symbol){
this.symbol = symbol;
}
public void setHPossistion(int x){
this.hPossistion = x;
}
public void setVPossistion(int y){
this.vPossistion = y;
}
public void setEnergy(int energy){
this.energy = energy;
}
public void setID(int i){
this.iD = i;
}
public void setDescription(String d){
this.description = d;
}
//getters
public String getSpecies(){
return this.species;
}
public String getName(){
return this.name;
}
public char getSymbol(){
return this.symbol;
}
public int getHPossistion(){
return this.hPossistion;
}
public int getVPossistion(){
return this.vPossistion;
}
public int getEnergy(){
return this.energy;
}
public int getID(){
return this.iD;
}
public String getDescription(){
return this.description;
}
public String toString(){
String BugData;
BugData = name + " " + symbol + "\n" + species + "\n" + description;
return BugData;
}
}
enum Direction:
package finalversion2;
public enum Direction {
NORTH, EAST, SOUTH, WEST;
}
now im guessing I need to redraw my map each time i wish it to move using my enum based on a boolean response, i.e. call the printworld method but randomly move the bug. but wont that reprint my random ints?
please help. im very new to java.
Cheers in advance.

how can implementing a heap that each node is a class?

I want to crate a Heap structure that each node have 2 data , 1) string 2) int
so i think that each node must be a Class that's name is "heapNode" , but i have a trouble in swap method ,
please help me
import java.util.ArrayList;
public class MainHeap {
ArrayList<heapNode> heap;
MainHeap (){
new ArrayList<heapNode>();
}
public int getMin(){
return heap.get(0).data ;
}
private int parent(int pos) {
return pos / 2;
}
private void swap(int pos1, int pos2) {
heapNode temp =new heapNode();
temp = heap.get(pos1);
heap.get(pos1) = heap.get(pos2);
heap.get(pos2) = temp;
}
public void insert(int elem) {
int max = heap.size();
heap.get(max).data = elem ;
int current = heap.size() ;
while (heap.get(current).data < heap.get(parent(current)).data){
swap ( current , parent(current));
}
}
}
and this is my heapNode class
public class heapNode {
int data;
String fileName;
}
the swap method has error but i cant solve errors
Your swap code actually makes the objects point to different objects. It does not modify the positions in the arraylist itself. If using arraylist, you will have to remove an object from an index and set that object at a new index to swap or else you can use other data structure.
java.util.PriorityQueue<YourClass>

Categories

Resources