I'm doing the last challenge on this forum post called 'graduation' except in Java instead: http://www.cplusplus.com/forum/articles/12974/
I've basically stumbled across a problem where if I have an arrayList of bunny objects that spawns new offspring based on the amount of males and females, I need to give each new offspring a dynamic name for the list or the compiler goes mental and throws a ConcurrentModifierException (which I'm assuming is because it's trying to go through multiple objects that have the same variable name).
The only way I can think of is by making a Bunny object array like saying:
bunnyList.add(bunny[i + 1])
Where i is the kind of 'global' id for all the bunnies. But the problem is that if I add it to the list it's illegal. To be honest, I'm not sure why either since I set the array list to be of type bunny array rather than just plain old bunny.
public class Bunnies {
private static ArrayList<Bunny[]> bunnyList = new ArrayList<Bunny[]>();
private static Bunny[] bunny = new Bunny[500]; //gives it a kind of id
private static int i = 0; //global bunny counter
Bunnies(){
//init the game list.
initBunnyGameList();
}
private void initBunnyGameList(){
for (int i = 0; i < 5; i++){
bunny[i] = new Bunny();
bunnyList.add(bunny[i]); //ILLEGAL :(!
}
}
}
Also doing it this way seems like a massive waste of memory to create an array space for 500 possible bunny objects only to ever use ONE space as an identifier. But I can't seem to think of a way to name each variable dynamically in any other way. Really, what I need is a way to generate variables with a number on the end when I make a bunny so they're all individual no matter what.
Any suggestions hombres?
bunny[i] is actually a Bunny object, not an array of Bunny objects.
private static ArrayList<Bunny[]> bunnyList = new ArrayList<Bunny[]>();
should be
private static ArrayList<Bunny> bunnyList = new ArrayList<Bunny>();
Related
I'm trying to update an array list and running into errors that I can't seem to shake (having reviewed a number of similar questions here).
Main Class
public static void main(String[] args) {
ArrayList<Player> PLAYERS = new ArrayList<Player>();
PLAYERS.add(new Player("char1", 10, "A"));
PLAYERS.add(new Player("char2", 20, "B"));
Then late, as the result of a loop (which is running without issue), I'm trying to update one of the above entries with-
PLAYERS.set(index, ("char1", variable, variable));
That last line is flagging errors
Player Class
public class Player {
public String character;
public int money;
public String reference;
Player(String character, int money, String reference){
this.character = character;
this.money = money;
this.reference = reference;
}
}
I've tried a few different way of updating, including using getters/setters, and having the different objects in the array being variables in their own right, but can't seem to work it out.
PLAYERS.set(index, ("char1", variable, variable));
Is not valid Java syntax. You most likely mean
PLAYERS.set(index, new PLAYER("char1", variable, variable));
Also, please adhere to standard Java naming conventions: PLAYERS should be players.
Your ArrayList doesn't contain multiple data types. It holds objects of Player and only Player type, and you appear to be trying to over-complicate things. You simply get your Player from the ArrayList and then modify it.
Player p = players.get(i);
p.setName("foo");
p.setMoney(50);
The compiler is correct. It doesn't know what you mean by ("char1", variable, variable) .
Try updating it with new Player("char1", variable, variable);
i have an array of strings which i want to convert to int, pretty simple and straightforward here is the code :
public static void main(String[] args) {
String myarray[]=readfile("[pathtothefile]");
int mynums[] = new int[myarray.length];
for (int i=0;i<myarray.length;i++){
mynums[i]=Integer.parseInt(myarray[i]);
}
System.out.print(Arrays.toString(mynums));
}
But the Problem here is, if i initialize "mynums" like this: mynums[]=null; i get NullPointerException on the following line:
"mynums[i]=Integer.parseInt(myarray[i]);"
what i have to do to solve it is
int mynums[] = new int[myarray.length];
here someone explained why it happens but i dont know how to initialize now! i mean sometimes i dont know how big my array can get and i just want to initialize it. is it even possible?
In Java everything is a pointer behind the scenes. So when you do mynums[]=null, you are pointing to a null. So what is null[i]? That is where your NPE comes from. Alternatively when you point it to an array, then you are actually accessing the i'th element of the array.
You have to first initialize the array because it allocates memory depending on the array size. When you want to add for example an integer to an array it writes the int into previously allocated memory.
The memory size won't grow bigger as you add more items.( Unless you use Lists or Hashmaps, ... but it's not true for generic arrays)
If you don't know how big your array will be, consider using SparseIntArray. which is like Lists and will grow bigger as you add items.
Briefly, in java an array is an object, thus you need to treat it like an object and initialize it prior to doing anything with it.
Here's an idea. When you're initializing something as null, you're simply declaring that it exists. For example ... if I told you that there is a dog, but I told you nothing about it ... I didn't tell you where it was, how tall it was, how old, male/female, etc ... I told you none of its properties or how to access it, and all I told you was that there IS a dog (whose name is Array, for sake of argument), then that would be all you know. There's a dog whose name is Array and that is it.
Typically, arrays are used when the size is already known and generally the data is meant to be immutable. For data that are meant to be changed, you should use things like ArrayList. These are intended to be changed at will; you can add/remove elements at a whim. For more information about ArrayList, read up on the links posted above.
Now, as for your code:
public static void main(String[] args) {
ArrayList<int> myInts = new ArrayList<int>();
// define a new null arraylist of integers.
// I'm going to assume that readfile() is a way for you get the file
// into myarray. I'm not quite sure why you would need the [], but I'll
// leave it.
String myarray[] = readfile("[pathtothefile]");
for (int i = 0; i < myarray.length; i++) {
//adds the value you've specifed as an integer to the arraylist.
myInts.add(Integer.parseInt(myarray[i]));
}
for (int i = 0; i < myInts.size(); i++) {
//print the integers
System.out.print(Integer.toString(myInts.get(i)));
}
}
What if you don't use an array but an ArrayList? It grows dynamically as you add elements.
In java how to use class variables in methods?
this is the code that I have
public class ExamQ3a {
String[] descriptionArr = new String[50];
static int[] codeArr = new int[50];
public static void displayItems(int count, int[] codeArr,
String[] descriptionArr) {
count = this.codeArr.length;
for (int i = codeArr.length; i < codeArr.length; i--) {
}
}
}
The line that is being highlighted here is the count = this.codeArr.length; the error that I am getting is that the non-static variables cannot be referenced from a static context. But I already made the variable static. So what gives?
So as per request only! not that I want to ask the whole question, just to know why I want to use static, this is a practice question
You are to develop a simple application system to manage the inventory
in a company. The system should be able to maintain a list of up to 50
items. Each item has a unique integer code and a description.
(a) Write Java statements that declare and create two arrays to store the
code and the description of the items.
(b) Write Java method with the following method signature:
public static void displayItems(int count, int[] codeArr, String[] descriptionArr)
This method displays the code and description of all items in the company
in tabular form with appropriate column heading.
Parameters: codeArr: the array that stores the codes of the items
descriptionArr: the array that stores the descriptions of the items
count: the number of items in the system
There is no this in the static world. Get rid of it. To explain, this refers to the current instance, and when you're dealing with static methods or variables, you're dealing with items associated with the class, not with any one particular instance. So change the code to:
count = codeArr.length;
Edit 1
As an aside, you don't want to bunch up your closing braces like } } } which makes your code very difficult to read and follow. White space is free, so might as well use it judiciously to improve code readability.
Edit 2
You state:
so how would I reference the array codeArr to the class variable codeArr?
You're inside of the class, and there's no need to use the class variable name here since it is assumed to be used. Just use the static variable or method name and you should be golden.
Edit 3
Your use of static for this type of variable gives the code a bad smell. I'm thinking that your entire program would be much better off if this were an instance variable and not a static variable. For more discussion on this, you may tell us why you decided to make the variable static.
Is you're going to reference a static variable having the same name as a method parameter you prefix the static variable with the name of the class. In this case it would be ExamQ3a.codeArr.
The other way to handle this is to pick different names for your method parameters, or start using a common prefix for instance/static variables.
Another point to note is that, in the following piece of code statement1 will never be executed:
for (int i = codeArr.length; i < codeArr.length; i--) { statement1; }
it should be either
int length = codeArr.length;
for (int i = 0; i < length; i++) { ... }
or
int length = codeArr.length;
for (int i = (length-1); i > -1 ; i--) { ... }
I am having some issues withs objects within an array working as one object rather than seperately as intended. For example
boardArray = new object[4];
workingBoardArray = new object[4];
boardArray[0] = new board(boardA);
boardArray[1] = new board(boardB);
boardArray[2] = new board(boardC);
boardArray[3] = new board(boardD);
int selectedBoard = selectBoard(boardArray);
workingBoardArray[0] = boardArray[selectedBoard];
workingBoardArray[1] = boardArray[selectedBoard];
workingBoardArray[2] = boardArray[selectedBoard];
workingBoardArray[3] = boardArray[selectedBoard];
workingBoard[0].moveUp();
workingBoard[1].moveRight();
workingBoard[2].moveDown();
workingBoard[3].moveLeft();
This code creates a set of 4 boards, finds the desired board, copies that board into the working board array and then shifts each working board in a new direction. The problem is that the boards all act together. So if I do moveUp() on workingBoard[0], workingBoard[1] is also moved up. Is there any way around this, I feel like I am missing some fundamental understand or a really silly mistake.
I also tried using a copy constructer like
workingBoard[0] = new Board(boardArray[selectedBoard].getBoard);
Which retrieves all essential board information and creates a new board with it, but that doesnt seem to affect anything. Any help would be great
Look at this code:
int selectedBoard = selectBoard(boardArray);
workingBoardArray[0] = boardArray[selectedBoard];
workingBoardArray[1] = boardArray[selectedBoard];
workingBoardArray[2] = boardArray[selectedBoard];
workingBoardArray[3] = boardArray[selectedBoard];
That's setting all four array elements to be references to the same object. So yes, when you modify that object by calling moveUp() or whatever, that change will be visible via all the elements in the array.
It sounds like you may want to create a copy of the board each time. Depending on what your board type (which should be called Board to follow naming conventions) does, you may want to just implement Cloneable (quite possibly overriding the clone() method) or provide some other sort of copying operation.
Are you aware of the difference between a reference and an object in Java, and that the array only contains references, not objects? (Likewise any variable value will only be a reference rather than on object.) It's really important to understand how objects work in Java. For example:
StringBuilder a = new StringBuilder();
StringBuilder b = a;
a.append("Foo");
System.out.println(b); // Still prints "Foo"
Here we've got one StringBuilder object, even though there are two variables (a and b) whose values refer to that same object.
... copies that board into the working board array and then shifts each working board in a new direction.
Actually you don't copy the board. There is only one board instance which is referenced four times from workingBoardArray. To make copies of the board you have either to implement the clone method or provide a custom copy method.
For example if you implement the clone method you could write:
workingBoardArray[0] = boardArray[selectedBoard].clone();
I am a beginner with java, and I was wondering is if is possible to name and create an array from the value of a string.
Here is what I have:
public static void array(){
createArray(array1, 100, 100);
}
public static void createArray(String name, int r, int c) {
int[][] name = new int[r][c];
}
I hope that explains itself. Thanks
EDIT: The code above does not work. I just want to know if it is possible to do what is above
EDIT2: As a beginner with java, I am just watching tutorials, and creating programs with what I learned to make sure I understand what is being taught. I first created a program which creates s multidimensional arrays. It then calls a method which assigned values to the array, (row+1)*(column+1). This makes a table much like a multiplication table. Then it displays the table to the screen.
After I created that program, I wanted to be able to create arrays much like I assigned the values to it. So i asked this question...
Here is my code:
public static void array(){
int[][] array1 = new int[100][100];
int[][] array2 = new int[20][20];
setArrayValue(array1);
setArrayValue(array2);
drawArray(array1);
System.out.println();
drawArray(array2);
}
public static void setArrayValue(int x[][]){
for(int row = 0; row<x.length; row++){
for(int column=0; column<x[row].length; column++){
x[row][column]= (column+1)*(row+1);
}
}
}
public static void drawArray(int x[][]){
for(int row=0; row<x.length; row++) {
for(int column=0; column<x[row].length;column++){
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
}
Your concept doesn't make sense.
You might want to use a Map<String, int[][]>, which will map names to arrays.
What you are trying to do is not possible in Java. In the createArray method, name is of type String and cannot be redeclared as an int array.
Perhaps you are interested in a Map that uses String objects as keys? The values could be int arrays (or any other object).
No, you can't do that.
Variable names are not variable in Java.
Furthermore, local variables even lose their names when the code is compiled. Variable names are just a help for the programmer to distinguish between variables.
Nop can't be done. Variable names need to be known before hand.
No, it is not possible. You might be able to accomplish your task with a TreeMap or another Map implementation instead.
Instead of saying
name = something;
You would say
map.put(name, something);
Instead of
name[0] + 7
You'd say
map.get(name)[0] + 7
As stated by others - this cannot be done. That is because Java compiler needs to know exact name of a variable at the compile time. This is mandatory, since otherwise Java compiler wouldn't know which variable you are addressing, so it couldn't perform, for instance, type-safety checks.
However, if you just wish to stamp your variable with some unique ID, I guess the solution is closest to what has been stated by SLaks. Simply use Map, and You should be good. Example below.
Map<String, int[][]> myMap = new HashMap<String, int[][]>();
myMap.put("someUniqueName", new int[][] {{0,0}, {1,1}});
and later on:
int[][] array = myMap.get("someUniqueName");
Hope that helps achieve what You want.
Strictly: almost ;-) You can add a dynamic field in a class, which could be an array, using AOP. But...
It's difficult.
This solution is too complicated in most cases. You could probably solve your real problem in a much easier way.
Some advice: start with the beginning... and try using List (interface) / ArrayList as much as possible unless you have some pretty good reason to use an array.