I'm working on a method that takes as input a two dimensional array, a character and 2 integers giving the location of the character in the array. I have to throw an exception whenever the array is full at the location i'm trying to access, or whenever i'm trying to access a location that is out of bounds. Java is giving me a weird error in relation to how I have written my code. I am not sure how to access a certain element from a two dimensional array. I have attached a screenshot of my code and the exception I get.
Thank you in advance! Here is the image
It may be preferable to copy and paste the code and the Exception straight to the question body with monospace formatting for easier readability.
The charAt function is expected to be called on a String object. A char[][] array is not a String object, so the code won't compile successfully. Depending on your familiarity with Java you may want to read up on the difference between a class object (such as an instance of the String class) and an array of primitive types (such as char).
Tutorial page explaining arrays: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Tutorial page explaining classes:
https://docs.oracle.com/javase/tutorial/java/javaOO/index.html
If you're trying to access a char from a two-dimensional char[][] array, just think of it like accessing an array of arrays. char[x] will get you the "row" containing the element you want and char[x][y] will get you the specific element in that "row" of elements.
Since your array is a char array you do not need to put board.charAt[x][y] just board[x][y]. Also the finally bit is always executed so if you put illegal values for x or y you will still get an error. Furthermore you are not writing the character referenced by the variable c to the array, you are writing the character (letter) c into the board.
You can use the second if statement with an else to put the character in the array and avoid the finally altogether.
if(board[x][y] != ' ') throw new IllegalArgumentException("Your message");
else board[x][y] = c;
which should go inside the first if that you've gotten.
Another approach is to use catch after the try because trying to access an element outside of the array will throw an Exception anyway.
Related
I have a JSON file that, among other things, contains various 2D arrays. Here is a link to a copy of the file. I want to load things such as "floor" into an int[][] array. I can't seem to find any way to do that. I might also be storing the array incorrectly, I'm not sure. I create the JSON file with a python script.
When I use processing's "loadJSONObject" function and access "floor", it says that it is a "processing.data.JSONArray" but I can't index it like a normal array. If I try to, it gives the error "The type of the expression must be an array type but it resolved to Object"
If I try to index it with ".getIntArray" like in this example, it gives the error "The function getIntArray() does not exist."
Here is some code, since I can't link pastebin without it:
JSONObject currentLevel;
currentLevel = loadJSONObject("assets/levels/test_level.json");
println(currentLevel.get("floor").getIntArray());
Any help is appreciated, thanks.
From the documentation, one level up:
getJSONArray(): Retrieves the JSONArray with the associated index value
After we get the floor data (e.g. floor = currentlevel.getJSONArray("floor")), it is itself an array of arrays of integers. Processing represents this with its JSONArray type, which apparently does not support indexing. We also cannot convert it to a plain array of integers, because it doesn't represent one - in the same way that we cannot treat an int[][] as if it were an int[] in Java.
Instead: use getJSONArray on floor to get the individual arrays of integers; and those can then be converted using getIntArray.
You need to do it like this: using getJSONArray()
JSONObject currentLevel;
currentLevel = loadJSONObject("assets/levels/test_level.json");
JSONArray array = currentLevel.getJSONArray("floor");
print(array)
Ref:
JSONArray_getJSONArray
Im checkin a code in c++ and i'm trying to "translate" it to java. i wonder what this line does... (both are int arrays)
frequencies[values[i]]++;
and how can i translate it?
This is the code I extrated the line from
https://github.com/Tomaszal/HackerEarth/blob/master/Data%20Structures/Stacks/Fight%20for%20Laddus/main.c
I believe it gets the value from the i-th element in the values array, searches for it in the frequencies array and add 1+ to the index...I don't really get it
This was my attempt to the code above
int y=values[p];
frequencies[y]=frequencies[y]+1;
It gets the value from i-th element in the values array and passes this value as an indexer to frequencies array and increments the returned value by 1. A perfect translation would be
Increment the (i-th value)th value of frequencies by 1.
and it surely works the same in Java. You don't need to convert it to any other statement(s) in Java to work.
I'm having trouble finding a solution in parsing out a particular part of each item in an Arraylist.
The Arraylist contains strings in both these formats:
http://some-url.com/that/goes-to-some-place-abc-defg/api/xml
http://some-url.com/that/goes-to-somewhere-zyxw-vut/api/xml
The key point is that the string won't change, the only thing that will be different in each of these is the "abc-defg" and "zyxw-vut". Note that they may be anything of varying length. This is the part I need to parse out to use elsewhere.
Only idea I've had is writing something to parse out everything after the 5th hyphen up to the next "/" for the former and the 4th to the next "/" for the latter.
I'm not sure how to do this though and there's likely a better method I haven't thought of.
Does anyone have any ideas on how to go about doing this?
You may use split("\\/") ;
This will return an array of String objects split along the / separator.
String.split(String regex)
For example for your String : http://some-url.com/that/goes-to-some-place-abc-defg/api/xml
This will return an array of size 7 , the content of the array would be :
http:
some-url.com
that
goes-to-some-place-abc-defg
api
xml
What you want is the index 4 of this array.
Note that index 1 is empty, this comes from the split of the // part.
You could just save the "random" parts in the ArrayList. This would save memory since the rest of the string is always the same:
ArrayList<String> list = new ArrayList<String>();
//Add your random parts
list.add("abc-defg");
list.add("zyxw-vut");
/* ... */
And when you want to get a full link from the list, you use a helper method:
private String getLinkFromList(int index) {
if (list == null || index < 0 || index >= list.size())
return null;
return "http://some-url.com/that/goes-to-somewhere-" + list.get(index) + "/api/xml";
}
A few notes:
This solution also has a few downsides: Memory is always allocated when the getLinkFromList(int) method is called. When you save the full link in the ArrayList and always just use the get(int) method from the ArrayList, you have a slight performance gain. If that list is not larger than a few MegaBytes and your code is only running on (modern) computers, then you should prefer saving the full link.
But when your code is running on an android phone (or when your list is a few GigaBytes large), where memory is still an important thing to consider, then you should make your list as small as possible and use my method as shown above.
This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 7 years ago.
I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and printed every element, it shows they are still 0s.
for(int num:a)
num=1;
But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try failed? And why it works when i print them? Thanks~~~
for(int num=0;num<a.length;num++)
a[num]=1;
for(int n:a)
System.out.println(n);
Your first loop declares a local variable which only exists inside that loop. Its value iterates over every value in the array. A new memory location is reserved temporarily and given the name "num". Changing contents of that memory location does not modify the values in the "a" array.
Your second loop explicitly accesses memory allocated for the array "a" and changes their contents.
These loops are different. Both in functionality and operations.
The first one - an enhanced-for loop - is giving you each element in the array referenced by the variable a. It is not exposing anything for you to mutate, so assignments to a have no effect on the actual value in the array.
The second loop is simply going through all of the elements in the array, but you are directly working with the array itself at all times, so mutating the values is perfectly possible.
To put this in other terms:
The enhanced-for is going through the array, and providing you a value to use. That value, while originally provided by the array, has no connection to the array otherwise. Any modifications made to the value would not propagate to the array.
The alternative loop is only ever accessing the array contents directly, where it is perfectly possible to make modifications and reassignments to the array.
Thus, if you ever want to set the values of an array to anything other than their default value, then using the second approach is the way to go.
Or...you could use Java 8's Stream API and come up with something like this:
IntStream.iterate(1, (x) -> 1).limit(100).toArray()
I have a 2D array and I want to grow it. I have copied it into a new array but how do I fill it with the contents from the previous array?
if (row == data.length) {
newData = Arrays.copyOf(data, 2 * data.length);
}
Are you trying to grow it, and then continue manipulating it in later stages of your code?
For example:
You have an array of size 4, you put 0 1 2 3 in it, now it's full, you want to double the size, and then continue adding numbers like 7 8 9 in it.
If that's the case all you need to do is assign newData to your previous array name, which by the example above is 'data'.
if (row == data.length)
{
newData = Arrays.copyOf(data, 2*data.length);
data = newData; //assigns the newArray to the previous variable name
}
If on the other hand you mentioned you wanted a 2D array. Which is an array of arrays of a certain type, then your code should work for 2D arrays too.
There will however be null values in the newly created array slots (eg you have a 2D array of ComplexNumber classes, and if you try to access those classes and call a method like GetImaginaryValue()) you will get a null exception.
As the xscanpix mentioned, your code works, if what we assume you to do is right. Please edit your question if it's not the case.
If it's not what you're looking for I apologize for misunderstanding. I'm going off by the rep you have that you're a new user to SO (like me) and might just be getting started on Java.
How is this code not doing what you want it to do? The java API doc for Arrays.copyOf states that it returns:
'a copy of the original array, truncated or padded with nulls to obtain the specified length' (depends on the type of array)
Edit:
Please post more code or it will be hard to give a reasonable answer.
What does this sentence mean?
"I have copied it into a new array but how do I fill it with the contents from the previous array"
You can try following line to realize this task. dataStart corresponds to the starting position in the source array and newDataStart corresponds to the starting position in the destination array.
System.arraycopy(data, dataStart, newData, newDataStart, data.length);
If you need to extend your array dynamically, you may take a look at ArrayList or Vector.