I'm having an issue with scope in an if statement, at least, I'm pretty sure that is where my error is, and I'm not sure of how to fix the issue (I'm pretty new at programming).
Basically, it seems that if I declare something within an if statement, the variable (in this case, an array of structs) does not exist outside of the if statement. However, I really need the declaration for the array to be inside of an if/else because the size of the array is dependent upon N, so how can I fix this error?
The program is in Java, and I'm using Eclipse. Any insight is greatly appreciated.
//declare an int (used in determining array length)
int N = 4;
//declare instance of MyClass
MyClass myClass = new MyClass();
//declare and array, then initialize each struct in that array
if(N <= 26){
MyStruct array[] = new MyStruct[260];
for(int i = 0; i < array.length; i++){
array[i] = new MyStruct();
}
}
else{
MyStruct array[] = new MyStruct[N*10];
for(int i = 0; i < array.length; i++){
array[i] = new MyStruct();
}
//lots of other code goes here of stuff that needs to be done before myMethod can be called
//call a method in myClass that requires 'array' to be passed in
myClass.myMethod(array); // ERROR - ARRAY CANNOT BE RESOLVED TO BE A VARIABLE
You need to move the array declaration MyStruct array[]; outside of the if block. You answered your own question, in fact, when you declare a local variable inside a block (a piece of code surrounded by {}), the variable will only be visible inside that block, as per the scoping rules of the Java language.
What you can do inside the if or else blocks, is instantiating the array to the correct size, like this:
MyStruct[] array;
if (N <= 26) {
array = new MyStruct[260];
for (int i = 0; i < array.length; i++) {
array[i] = new MyStruct();
}
}
else {
array = new MyStruct[N*10];
for (int i = 0; i < array.length; i++) {
array[i] = new MyStruct();
}
}
An even shorter solution would be:
MyStruct[] array = new MyStruct[N <= 26 ? 260 : N*10];
for (int i = 0; i < array.length; i++) {
array[i] = new MyStruct();
}
Others have answered why it's a problem and how to avoid it, but I'd actually change the approach anyway. Currently you have two blocks with repeated code - why not avoid that?
int length = Math.min(N, 26);
MyStruct array[] = new MyStruct[length];
for(int i = 0; i < array.length; i++) {
array[i] = new MyStruct();
}
MyClass myClass = new MyClass();
myClass.myMethod(array);
(Note that the name MyStruct has connotations which may well not be appropriate in Java. I realize it's just a dummy name, but Java doesn't have anything like a "struct" from C or C#. Just in case you're expecting something else...)
Put the array declaration outside the scope of the if statement.
Related
I just began studying java. One of the tasks was to create a function to create a reverse 2-dimensional array, for example, if the input array was {1,2}{3,4}, the new array must be {4,3}{2,1}. The code below is the method I created. The problem is that the old array d is affected by the loop along with c, so, in this case, it copies half of the values into c, but also replaces the last half of d, so the second half of c is just a mirrored first half, basically, in the example case both c and d will be like this in the end: {4,3}{3,4}. I checked c==d and c.equals(d) after cloning, both show false.
Also, I tried using Arrays.copy, the result was the same. Plus I want the method to work on the arrays that can have their sub-arrays with different lengths, for example, {1,2}{3}{4,5}, and I don't know if it'll work on such arrays.
static int[][] reversematrix(int[][] d) {
int[][] c = d.clone();
for (int i = d.length-1, x = 0; i >= 0; x++, i--) {
for (int j = d[i].length-1, y = 0; j>=0; y++, j--) {
c[x][y] = d[i][j];
}
}
return c;
Can you tell me how to make d(imput array) unaffected by the method/loop? I think the problem is in copying, so I'd love to know a proper way of copying a 2D array into a new object, but if it is in something else, please tell me waht it is.
UPD: Thanks to #sascha the solution was found. Here's the code if someone is interested:
static int[][] reversematrix(int[][] d) {
int[][] c = new int[d.length][];
for (int i = d.length-1, x = 0; i >= 0; x++, i--) {
c[x] = new int[d[i].length];
for (int j = d[i].length-1, y = 0; j>=0; y++, j--) {
c[x][y] = d[i][j];
}
}
return c;
}
I would like to know how array[array[i]]++ works in java.
I wrote the code, and want to know how this count integer array is working here
int[] counts = new int[201];
for (int i = 0; i < d; i++) {
counts[array_inside[i]]++;
}
and
also would like to know if i does like below how count array values will be written and left or right shift its values
for(int i = j; i < array_inside.length; i++){
count[array_inside[i-j]]--;
count[array_inside[i]]++;
}
Consider it as two operations (because it is). This
counts[array_inside[i]]++;
is equivalent to
int p = array_inside[i];
counts[p]++;
Im trying to make every "ADJEKTIVER" strings in the storyList array into random strings from my adjectivesList array. When I'm trying to compile, I only get the error: cannot find symbol- variable. With .length as the variable/attribute. Been searching for a solution quite a while now
ArrayList<String> storyList = new ArrayList<String>();
storyList = reader.getWordsInFile(storyFilename);
ArrayList<String> adjectivesList = new ArrayList<String>();
adjectivesList = reader.getWordsInFile(adjectivesFilename);
for (int index =0; index < storyList.length; index++)
{
storyList[index] = storyList[index].replace("ADJEKTIV", adjectivesList[random.nextInt(adjectivesList)]);
}
writer.write(adjectivesList, outputFilename);
use storyList.size() method instead of storyList.length
for (int index =0; index < storyList.size(); index++)
Arralist or List doesnt have any property named "length". use size() method instead
Arrays have a public final int property called length, that holds the number of elements in the array, arrays can't change how many elements they have in Java.
Which brings me to ArrayList having a collection that can change the number of elements it has is useful, but it's not magic(I would've liked someone to tell me this). It has an Array of type E[] I will call this internal array arr.
When you push an element to an ArrarList
public boolean add(E e) {
E[] temp = new E[this.arr.length];
for (int i = 0; i < this.arr.length; i++)
temp[i] = this.arr[i];
this.arr = new E[this.arr.length + 1];
for (int i = 0; i < this.arr.length; i++)
this.arr[i] = (i == temp.length ? e : temp[i]);
temp = null; // free temp or let it fall out of scope
return true;
}
// Removing is easy too
public E remove(int index) { // I'm just doing the first of the overloaded methods, in api
E returnValue = this.arr[index];
E[] temp = new E[this.arr.length - 1];
for (int i = 0; i < this.arr.length; i++)
if (i != index) temp[i] = this.arr[i];
this.arr = new E[this.arr.length - 1];
for (int i = 0; i < this.arr.length; i++)
this.arr[i] = (i == temp.length ? e : temp[i]);
temp = null; // free temp or let it fall out of scope
return returnValue;
}
The being able to change the length forces it to be accessed in a dynamic way in Java via a method called size in this case.
public int size() {
return this.arr.length;
}
Java exists both as a standard and as an implementation, the former might be implemented such that Strings are mutable so making String have a length method makes code more compatible between the implementations of the standard, as implementations(not necessarily those of Java) have been known to deviate, so making them more compatible makes sense for the Java devs.
As for why ArrayList uses size() as the method name, while String uses length(), and Array uses length, I don't know although in my opinion(warning opinions ahead) it's not unreasonable that accessing the lengths got implemented the way they did, and the Java devs felt locked in, because changing the spec would also required changing the code in question.
public int length() {
return this.arr.length;
}
All code shown is merely for demonstration purposes, and comes as is, and is without warranty of any kind.
I will have a series of random arrays similar to.
array1[] = {1,2,3,0,0,5,6}
array1[] = {1,2,0,0,4,5,6}
I want them to end up like, so I replace the first 0 with X.
array1[] = {1,2,3,X,0,5,6}
array1[] = {1,2,X,0,4,5,6}
the code I'm using replaces all zeroes giving instead of just one.
array1[] = {1,2,3,X,X,5,6}
array1[] = {1,2,X,X,4,5,6}
Which isn't what I'm looking for. I'd be happy just replacing either one but only one.
The code I'm using,
for(int i=0; i<array.length; i++){
if(fruit[i] == 0)
fruit[i]=X;
}
Hope that was clear, thanks for any help! Being stuck at this for a little while now.
Try using break.
for(int i = 0; i < array.length; i++) {
if(fruit[i] == 0) {
fruit[i] = X;
break;
}
}
This will ensure only one is changed, max.
I've a slight problem. I'm taking every element in a sparse matrix and putting it into a 1d array named 'b[]'. For example:
00070
00400
02000
00050
10000
Becomes: 0007000400020000005010000
The code below works in that at a given point within the inner-most loop b[] has the correct value as shown below. My problem is that outside of the inner-most loop b[] has a value of:
b[] = 0000000000000000000000000
I cannot understand what I'm missing. It should also be noted that b[] is globally defined, and instantiated within the constructor of this class. The problem is that I'm trying to use this 1d array in another function, and every element within the array is set to 0.
public void return1dSequence() {
// Create paired objects (Pair class).
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
this.b[i] = a[i][j];
// System.out.print(b[i]);
if (this.b[i] == 0) {
pos += 1;
} else {
value = this.b[i];
ml.add(new Pair(pos, value));
pos += 1;
}
}
}
}
Thanks in advance for any replies,
Andre.
You're filling in b[i] for indexes i of your outer loop...
Each time in the inner loop, you overwrite b[i] with value a[i][j].
Last value of a[i] array is always zero.
That's why your b array is zero.
What you want is probably:
int counter = 0;
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
b[counter] = a[i][j];
counter++;
}
}
The first thing i want to mention is that u shouldn't declare your variables (a, b....) static. Maybe u got hit by a mean side effect after creating two instances of Sparse. Try to define them as non static and report if it still wont work.
Best regards
Thomas
Try removing this from each call to b[] if you want to access b[] as static.
Also, are you sure you are not overwritting b[] anywhere else in the code? This is most likely the issue because of the public static declaration. Try making it private and removing static and see if you still have the issue.