Creating an object of one class in another class? - java

I have two classses and I wonder why I always get an error when I try to create an object of class "Knoten" in a method of class "Graph".
Class Graph
public class Graph
{
static Knoten[] knotenliste;
public void punktHinzufuegen(int x, int y){
for(int i=0;i<Gui.zaehler;i++){
knotenliste[i]=new Knoten(x,y);
}
}
}
Class Knoten:
public class Knoten{
int xPos;
int yPos;
public Knoten(int x,int y){
xPos=x;
yPos=y;
}
}
Every time I call method punktHinzufuegen I get an error. Thanks for helping..

Your problem is a very easy problem to solve, so I'll give a short explanation/solution.
What your current problem is, is that you are not defining your knotenliste.
You should define it as the following field:
private static Knoten[] knotenliste = new Knoten[Gui.zaehler];
I would suggest that you do not use a static value but start working with either a fixed ArrayList (in order to index your graph points) or a Queue. Both of those can be found on the Java documentation if you're intested in reading about them.
What I would have done is the following:
public class Graph {
private final ArrayList<Knoten> knotenliste = new ArrayList<>(Gui.zaehler);
public void punktHinzufuegen(int x, int y) {
for (int i = 0; i < Gui.zaehler; i++) {
// Keep in mind that the List#add(int index, E element) will
// shift all the elements previously in the array to the right.
knotenliste.add(i, new Knoten(x, y));
}
}
}
With this you do not only stop abusing the static keyword, but you also have a more flexible Collection to save your Knoten in.

You haven't initialized your array and I think you are getting NullPointerException while adding elements. You need to initialize it before adding elements to it
static Knoten[] knotenliste = new Knoten[<SOME_INT_VALUE>];

Related

When I create a 2D array outside of my constructor, I'm not able to resize it, but when I create one inside of it, I'm not able to access it

I'm trying to create a method which will create an object which contains a 2D boolean array, with int parameters as the number of rows and columns. Then inside the class, I have methods that try to grab the length and width of that array. The two ways I tried to solve this problem were:
public GameOfLife(int rows, int cols) {
boolean[][] society = new boolean[rows][cols];
}
public int numberOfRows() {
return society.length;
}
In my tests, this attempt was giving me the error that society cannot be resolved to a variable. Then I tried:
private boolean[][] society;
public GameOfLife(int rows, int cols) {
boolean[][] temp = new boolean[rows][cols];
society = temp;
}
EDIT: Oops, forgot to add my method for numberOfColumns:
public int numberOfColumns() {
return cols;
}
But the issue with this one was that it was returning 0 instead of 4 when I tried:
#Test
public void FailedTestingRowsAndCols(){
GameOfLife g1 = new GameOfLife(4,4);
assertEquals(4, g1.numberOfColumns());
}
I'm rather new to this, so I apologize if this is a dumb question, but I'm not really sure about all the details of where and when variables expire, which is giving me a lot of difficulties. THank you for any help!
When I create a 2D array outside of my constructor, I'm not able to resize it, but when I create one inside of it, I'm not able to access it
Take note that you will never be able to resize an array. An array once created has its size fixed. You are merely assigning your current array to reference to another newly created array (which gives you the illusion that you successfully resized it).
As for your question of not being able to access it is highly likely the variable you created exist within different scope.
You can use the following codes (which is very similar to yours), it works fine for me. Hence I am guessing your error does not actually comes from the code snippet you showed.
class TestRunner
{
public static void main(String[] args){
GameOfLife gol = new GameOfLife(5, 3);
System.out.println(gol.getColumns());
System.out.println(gol.getRows());
}
}
class GameOfLife
{
private boolean[][] society;
public GameOfLife(int rows, int cols){
society = new boolean[rows][cols];
}
public int getColumns(){
return society[0].length;
}
public int getRows(){
return society.length;
}
}
Output:
5
3
I don't see any problems with what you have posted so far. The below example works fine for me:
public class GameOfLife {
public static void main(String[] args) {
GameOfLife g1 = new GameOfLife(4,4);
System.out.println(g1);
}
private boolean[][] society;
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("GameOfLife{");
sb.append("society=").append(society == null ? "null" : Arrays.deepToString(society));
sb.append('}');
return sb.toString();
}
public GameOfLife(int rows, int cols) {
boolean[][] temp = new boolean[rows][cols];
society = temp;
}
}

Syntax error on "x", VariableDeclaratorld expected after this

class anyName
{
int Tcol = 0;
int fc = 0;
int x = 0;
float randx = (random(1, 1000));
float randy = (random (0, 600));
int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
anyName ranx1 = new anyName();
ranx1.x = 100;
Hi, I am trying to add a class/object to my code and it is not working. This is the class I have so far, but when I instantiate one object from that class (ranx1), and then try change one of the variables inside it (x), it says there is a error. Is there anything I need to change? I would really appreciate any help.
Since I instantiated an object from that class, how would I change the variables for the new object? For example, if in the class x = 0, then I made a copy and this time I want x to = 100, but all the other variables such as Tcol and fc to stay the same. I know this is possible because my teacher taught it, but it is not working right now for me.
ranx1.x = 100;
You need to declare your variables as "public" if you are trying to access from a class that is not in the same package.
I guess your problem is you are trying to access to that attribute from a class that is in another package, you should declare the atrributes as public to gain access to them. But this solution wouldn't be totally correct, a better approach is declaring them as private and creating public getters and setters to access/modify them.
Said that, you should post a working example, that piece code does not compile because you are trying to execute code that is out of any class... and I'm not sure what you are trying to do with the curly braces before the if clause.
when you careate a class, every member has a control access.
when you don't state the control access like:
public x;
protected fc;
private Tcol;
they all get default private.
you can't access private members from outside the class.
do:
class anyName
{
public int Tcol = 0;
public int fc = 0;
public int x = 0;
public float randx = (random(1, 1000));
public float randy = (random (0, 600));
public int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
whoever, i must point out that most times it's not recommended to set members access as public and you should learn about getter and setters.
now i hope the rest of your code is in a main function and in a main class, but if not it should be like so:
public class Main
{
public static void main(String[]args){
anyName ranx1 = new anyName();
ranx1.x = 100;
}
}
First of all you cannot access sub class veriables like that. If you want to access you should make this
public class ExampleApp {
class anyName
{
int x = 0;
}
public static void main(String[]args){
ExampleApp ea = new ExampleApp();
ExampleApp.anyName ranx1= ea.new anyName();
ranx1.x =100;
}
}
Or you can use them inside of the class with method
public void method() {
anyName ea = new anyName();
ea.x=100;
}
you cannot use your veriables private if you want to access them.Secondly if you want to use this libraries you cant use innerclass. Inside of innerclass you cannot access libraries because java sees it in diffrent package. If you make it public class and import Math you can use it otherwise you should make method for your ellipse, random .

Issue with using arrays in java?

So, I have a class Square and I am trying to use an array for it board. Here is my code:
public class Square{
public int pcolor;
public int contains;
public int xPos;
public int yPos;
Square(int xp,int yp,int pc,int cont){
xPos=xp;
yPos=yp;
contains=cont;
pcolor=pc;
}
};
Square[] board = new Square[64];
board[0].xPos=0;
This gives me unexpected token: [ on board[0].xpos=0;. Can anyone help me resolve this?
EDIT:
OK, I moved board[0].xpos=0; inside a method; now it gives me NullPointerException. What do I do?
You are trying to make a statement not inside a method or a static scope.
The statement board[0].xPos = 0; should [probably] be inside a method.
You also seem to have a redundant };
This code compiles just fine:
public class Square{
public int pcolor;
public int contains;
public int xPos;
public int yPos;
Square(int xp,int yp,int pc,int cont){
xPos=xp;
yPos=yp;
contains=cont;
pcolor=pc;
}
Square[] board = new Square[64];
}
To initialize [and access] elements in board - you will have to do it in a method or in the constructor.
Well, if you do this correctly you will get NullPointerException because you didn't create any object yet. My guess is you did some syntax error.
All the Squares in board are null and you're trying to access a field of a null Object...
You can initialize the array with:
for(int i = 0; i < board.length; i++)
board[i] = new Square(...something_here...);
Also, I'm not sure what you're trying to do, but you should consider using a Square[][]!

Luse Constructor With Variable Inside

I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).

Java: Adding to an array list

public class Maze
{
public static final int ACTIVE = 0;
public static final int EXPLORER_WIN = 1;
public static final int MONSTER_WIN = 2;
private Square[][] maze;
private ArrayList<RandomOccupant> randOccupants;
private Explorer explorer;
private int rows;
private int cols;
public Maze(Square[][] maze, int rows, int cols, int numTreasures, int numMonsters, String name)
{
int i;
this.maze = maze;
this.cols = cols;
this.rows = rows;
randOccupants = new ArrayList<RandomOccupant>();
for (i = 0; i < numTreasures; i++)
{
randOccupants.add(i) = new Treasure(this); //COMPILE ERROR
}...
Why can't I add this to the arraylist? I believe the java docs says that I'm doing this correctly.
You can do either:
randOccupants.add( i, new Treasure(this) );
...or...
randOccupants.add( new Treasure(this) );
Both are equivalent, since you're always appending the new element to the end of the array.
See https://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html.
First, Treasure would need to either inherit from RandomOccupant or implement it (if it is an interface).
Second, if you want to add it at a particular point in the list, the syntax is
randOccupants.add(i,new Treasure(this));
Although it's hard to see why you don't just do
randOccupants.add(new Treasure(this));
since the items will be added in order even if you don't specify a location.
You're trying to add a Treasure to an ArrayList of RandomOccupants, so unless Treasure is a RandomOccupant, that's not going to work. The given code does not make it clear whether Treasure is a subclass of RandomOccupant, so it's not possible from the code here to say whether that's part of the problem.
What you're actually doing is adding an int to the list here, which is definitely not a RandomOccupant.
ArrayList's add() method returns either boolean or void depending on the version that you're using, so you can't assign to it. You're using the method incorrectly.
The two versions of add() are:
boolean add(E e)
void add(int index, E element)
The second version inserts the element at the specified position, and the first one inserts it at the end. Presumably, what you're intending to do is this:
for(i = 0; i < numTreasures; ++i)
randOccupants.add(new Treasure(this));
But of course, that assumes that Treasure is a subclass of RandomOccupant. If it isn't, then you'll need to change the type of the ArrayList for it to hold Treasures.
Because it is not a RandomOccupant.
Because you're using the add method wrong. You would call:
randOccupants.add(new Treasure(this));

Categories