Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am making a Realm plugin for my server, and I am using a multiarray to detect the location of users portals, below is the code:
public static String[][][] realms;
#EventHandler
public void onPlayerInteract(final PlayerInteractEvent event) throws Exception {
if( event.getMaterial() == Material.NETHER_STAR ) {
int x = (int) event.getClickedBlock().getX();
int y = (int) event.getClickedBlock().getY();
int z = (int) event.getClickedBlock().getZ();
** realms[x][y][z] = event.getPlayer().getName();
createPortal();
}
}
I get a NullPointerException at the line with the '**', can someone please explain what I am doing wrong? I have googled 'java multiarrays', and they all seem to work the same way.
You are getting a null pointer exception because you haven't initialized the array.
You can initialize the array like this:
String string[][][] = new String[3][3][3];
you need to know what would be the length of the arrays, because if you try to access or save a value with an index that doesn't exists you are going to get a IndexArrayOutOfBounds exception
Array life cycle consists of three things
1. Array type declaration
2. Array initialization
3. Array utilization
But you have not declared an array rather you have just declared an variable and informed compiler that you wish to have an 3- dimensional array named "realms" of type "String" but you forgot to allocate that array in memory and there after relating its pointer to the variable.
Sample for Array declaration
public static String[][][] realms; /// array variable declared
/*now allocate the memory and point it to the array variable*/
realms = new String [<length index>][<breath index>][<height index>]
try this (replace length index, breath index, height index as per you)
public static String[][][] realms;
#EventHandler
public void onPlayerInteract(final PlayerInteractEvent event) throws Exception {
realms = new String [<length index>][<breath index>][<height index>]
if( event.getMaterial() == Material.NETHER_STAR ) {
int x = (int) event.getClickedBlock().getX();
int y = (int) event.getClickedBlock().getY();
int z = (int) event.getClickedBlock().getZ();
** realms[x][y][z] = event.getPlayer().getName();
createPortal();
}
}
Judging by your comments in other answers, I don't think a multidimensional array is the data structure you want. You suggest your indices are potentially unbounded (or at least very large) and can be negative, and will presumably only be sparsely filled. I think you therefore want an Octree implementation to store your data in. There's one available at http://www.java-gaming.org/index.php?topic=27334.0 - I've never used it, but have used the Quadtree implementation (basically the same thing with 2 dimensions rather than 3) successfully in the past.
Here's an example of how to initialize a multi array:
Initialize 2D array
The bottom of the accepted answer shows the syntax:
String[][] table = new String[5][5];
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Please can you explain to me if we want to add an element to a the end of a preexisting array how is it properly done.
I am having difficulty understanding the Littler class specifically the add method.
I understand that "Puppy[] temp = new Puppy[this.puppies.length + 1];"
We have a new array that is one greater in length than the puppies array (instance variable). "temp[i] = this.puppies[i];" assigns all the elements from the puppies array to the temp based on the indexes.
My confusion lies with line: temp[this.puppies.length] = puppy;
1.) What exactly is happening here?
In my mind I think that we are reassigning the last index position of this.puppies.length to the puppy parameter.
2.) Will that +1 (one size bigger) that was made, the extra index of the temp array on the line
"Puppy[] temp = new Puppy[this.puppies.length + 1];"
remain blank?
3.) Does "this.puppies = temp;" represent a shallow copy?
4.) What is this process called of making a bigger array and adding an object, do we have to do it every time (create an array one bigger).
5.) What happens if we don't, is there a situation where we don't have to make one bigger, or need a temp array? (I am just confused as to why we need it).
6.) What does an object of the class type mean? What does "private Puppy[] puppies;" mean exactly?
7.) Please can you help me decipher this code so I can understand. Especially with a hypothetical example if this.values.length was an array of a size of 5 elements (index 0-4).
//Class where add actions taking place
public class Litter {
private Puppy[] puppies;
public Litter() {
this.puppies = new Puppy[0];
}
public void add(Puppy puppy) {
Puppy[] temp = new Puppy[this.puppies.length + 1];
for (int i = 0; i < puppies.length; i++) {
temp[i] = this.puppies[i];
}
temp[this.puppies.length] = puppy;
this.puppies = temp;
}
}
First and foremost - arrays indices are 0 based. If you have an array of size 10, the valid array indices are from 0 to 9.
temp[this.puppies.length] = puppy
This stores the reference to some Puppy object (puppy) as the last element of the array. (since the length of temp is puppies.length + 1)
Will that +1 (one size bigger) that was made, the extra index of the temp array on the line [..] remain blank
No. The above assignment was made to the last element as arrays use 0-based indexing.
Does "this.puppies = temp;" represent a shallow copy?
No new object is created. After the assignment, both variables, this.puppies and the Puppy array (temp), point to the same object on the heap.
What is this process called of making a bigger array and adding an object, do we have to do it every time (create an array one bigger).
There is no general name for this. It is done here to add a new element to the array. Generally, to avoid this (often), a new array of double the size would be created.
What happens if we don't, is there a situation where we don't have to make one bigger, or need a temp array? (I am just confused as to why we need it).
Since arrays cannot be resized, you have to create a bigger array if you want to add a new object.
What does an object of the class type mean? What does "private Puppy[] puppies;" mean exactly?
puppies is an object that holds an array of Puppy objects.
Please can you help me decipher this code so I can understand. Especially with a hypothetical example if this.values.length was an array of a size of 5 elements (index 0-4).
This method is to add a new Puppy to the existing ones. Since arrays cannot be resized dynamically, it creates a new array(temp) and adds all the existing puppies. To accommodate a new Puppy, the created array size is one greater than the existing puppies. Then, it adds the passed Puppy instance as the last element of the array. The last line this.puppies = temp assigns the reference of the created array to the instance variable that points the puppies array.
i have two 2D arrays for a class called quiz. My logic of manipulating these arrays is not correct as i'm not getting the corrected output i expected. I would appreciate if someone can check my logic and help me figure out what i'm doing wrong:
Here are my arrays:
public String [][] questions ={
{"L1Q1","L1Q2","L1Q3"},
{"L2Q1","L2Q2","L2Q3"},
{"L3Q1","L3Q2","L3Q3"},
{"L4Q1","L4Q2","L4Q3"},
{"L5Q1","L5Q2","L5Q3"}};
public String [][] answers = {
{"A1Q1","A1Q2","A1Q3"},
{"A2Q1","A2Q2","A2Q3"},
{"A3Q1","A3Q2","A3Q3"},
{"A4Q1","A4Q2","A4Q3"},
{"A5Q1","A5Q2","A5Q3"}};
I also have two variables, one called numQuestion, and numQuiz. and I'm passing these two as indexes to the questions array. I'm also using these two indexes to in the answers array. I want to compare if the answer at the specific cell of the 2d array corresponds to the correct answer of the question. Here is a snipped of my code that i wrote to do that:
public void review(String answer) {
int y = questionNum;
int x = quizVal;
if( answer.equals(answers[x][y])){
currentQuestionCorrect = true;
} else {
currentQuestionCorrect= false;
}
}//end of review
my program is running and it's working, but the review method keeps saying that my answers are wrong when they are correct. can someone please help me
Have you checked that when you click on first line you set x to 0 and not to 1 ? Idem for column.
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.
I'm new to stack overflow so sorry for anything that might consider me a newbie.
I understand java to a certain degree, however, i am stuck on one thing i hope you guys can help me on.
I am in the process of making a floating point simulator and i am struggling on this section of the code.
I need the next part of the array [1] to reach the total length of the mantissa my knowledge with arrays in java are not exactly the best so any help would be much appreciated.
Thanks
public float toDecimal()
{
/**
* Convert Exponent and find shift
*/
char[] mantissaCharArray = mantissa.toCharArray();
int mantissaLength = mantissaCharArray.length;
float[] mantissaMultiplierArray = new float[mantissaLength];
mantissaMultiplierArray[0]= 1;
for (mantissaMultiplierArray[1];mantissaCharArray;mantissaMultiplierArray++)
{
//for loop to cover array from [1] to the lengthmantissa
}
//each one multiply current
}
Try this,
for (int i=(int)mantissaMultiplierArray[0];i< mantissaCharArray.length;i++)
{
//
}
mantissaMultiplierArray[0] will return float value.
So you want to run through each element of an array? You are right with the for loop, just wrote it wrong. It should go something like this;
for(int i = (int)mantissaMultiplierArray[0]; i < mantissaCharArray.length; i++)
{
System.out.println(mantissaMultiplierArray[i]);
}
Let me explain the setup of this for loop a bit more;
You are setting an integer value i to the first value of mantissaMultiplierArray. You are also parsing it as an int because it is a float, hence the (int)
You give i a limitation - the total size of the mantissaCharArray
increment i
In the for loop I have it set to print out the values of the mantissaMultiplierArray for each value of i, but yu can do whatever you want inside of it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am practicing Java and working on arrays. As arrays size can not be changed in run time, is it possible to make 2 arrays and in run time keep storing input in the first of and then when it is full, then move to the second array by if statement. I'm basic in Java so hope my code is in the right direction. Anyway it does not work but I just want to share my idea and see if it can work.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int[] arr1 = new int[5];
int[] arr2 = new int[10];
while(in.hasNextInt())
{
for(int i = 0; i <= arr2.length; i++)
{
if (i <= arr1.length) { arr1[i] = in.nextInt(); }
else arr2[i] = in.nextInt();
}
}
}
You should change your code to the following:
if (i < arr1.length) { arr1[i] = in.nextInt(); } //"<" instead of "<="
else { arr2[i - arr1.length] = in.nextInt(); } //decrement i by the size of the first Array
As denoted in the other answer/answers, there are plenty of more practical ways to do what you are trying to achieve, but non the less the above should let your code work as inteded.
This is not a good idea. If the second array overfills, you'll have problems such as exceptions and lost data.
I recommend using the ArrayList.
You can create one:
ArrayList<Integer> list=new ArrayList<>();
and add to it with:
list.add(new Integer(in.nextInt()));
With autoboxing you can skip the creation of an integer reference object and use:
list.add(in.nextInt());
Anyway it does not work ...
Yea. Pretty obviously.
... but I just want to share my idea and see if it can work.
No. Pretty obviously.
Sure you can put elements in the second array when the first array. But then you run into the same problem all over again when when the second array fills up.
The best solution is to use an ArrayList<Integer> (... or any kind of List<Integer>). That will take care of the problem of "growing" the list transparently and automatically.
If you insist on doing this with arrays, then the solution is to:
dynamically allocate a "new" array that is bigger than the "current" array,
copy the elements of the "current" array to the "new" array, and
assign the reference for the "new" array to the "current" array variable.
In fact, you could do all of this using Arrays.copyOf(int[], int).