Global Java array setting values to 0 - java

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.

Related

Variable changes without me using it

I have a problem, my variable tabOffrandes change without I change this so I don't understand. This is my code:
public static int[] tri_selection(int[] tab) {
int a;
for (int i = 0; i < tab.length; i++) {
for (int j = i + 1; j < tab.length; j++) {
if (tab[i] > tab[j]){
a = tab[j];
tab[j] = tab[i];
tab[i] = a;
}
}
}
System.out.println();
return tab;
}
public static Joueur[] offrande(int[] offrandes) {
int[] tabOffrandes = offrandes;
printTab(tabOffrandes);
int[] ordreOffrande = tri_selection(offrandes);
printTab(tabOffrandes);
The terminal respond:
8 - 3 - 5 - 1
1 - 3 - 5 - 8
The function printTab just print all of the numbers in int[], I think it's not very important to show this.
The problem in your code is that you refer to the same array in the memory, even if you provide different names for them.
This is only an assumption, but what I think you are trying to do by writing:
int[] tabOffrandes = offrandes;
is to create a copy of your original array, right?
To achieve this, you must write the code as:
int[] tabOffrandes = Arrays.copyOf(offrandes, offrandes.length);
This way, your original offrandes array will not be affected when you call the tri_selection function.
Not related to your question, but it might help you in the future. I'm not sure what's your implementation for printTab function. I assume that you manually iterate through the array and print the items? Just wanted to let you know that there is a shorter solution, by using Arrays.toString(...), in case you didn't know:
System.out.println(Arrays.toString(tabOffrandes));

Calculating the factorial of every element in an integer array

I need to create a Method that has 2 parameters in Java, upperborder and lowerborder. This method must create an array from the number 2 to the number 10.
Then I must implement another method, that calculates the factorial for a given number.
Then I must implement a third method that calculates the factorial for every element in the created array and test all these methods in a TestClass.
I know how to do this, but apparently I'm making some kind of a mistake in my code and it gives me the StackOverflow exception. I read the code a couple of times, but I can't seem to quite understand where I'm wrong.
package fakultaetinarray;
public final class FakultaetinArray{
private int i;
private int[] a;
private int j;
public FakultaetinArray(){
System.out.println("Given array : ");
createArray(1, 9);
System.out.println("Factorial for every element : ");
FakinArray();
}
public int fakRe(int n){
if(n == 1){
return n;
}
return n * fakRe(n - 1);
}
public void createArray(int untergrenze, int obergrenze){
this.a = new int[obergrenze];
for(this.j = 1; j <= a.length; j++){
a[i] = j + 1;
System.out.println(a[i]);
}
}
public void FakinArray(){
a[0] = 2;
for(i = 1; i < a.length; i++){
int fak = fakRe(a[i]);
a[i] = fak;
System.out.println(fak);
}
}
}
The reason you're getting StackOverflowErrors is due to your recursive method not having a case when n == 0.
The reason that your values are coming in as 0 is due to how you're constructing your loop.
for(this.j = 1; j <= a.length; j++){
a[i] = j + 1;
System.out.println(a[i]);
}
It's unclear why you're using j here at all, and i is initialized to its default value of 0, so in all reality, you're only ever filling one element of your array with a positive value and all of the others are at zero.
You need to reconsider how your loops are constructed. I would strongly encourage you not to make them fields, but declare them as part of the loop construct instead.
if(n == 1){ is not a strong enough condition to block the recursion: n can go below 1. In your particular case, you have a situation where n is 0.
Consider unwinding the recursion to a simple loop in any case. As a rule of thumb, recursion is not good for O(N) stuff.

Java ArrayIndexOutOfBounds

Currently working on a student project. I want to figure out the highest number and sort it by bubble sort, the number is parsed from a JLabel, but I get this error everytime. Here is a code snippet:
JLabel[] wuerfelsummen = new JLabel[7];
wuerfelsummen[0] = player1_wuerfelsumme;
wuerfelsummen[1] = player2_wuerfelsumme;
wuerfelsummen[2] = player3_wuerfelsumme;
wuerfelsummen[3] = player4_wuerfelsumme;
wuerfelsummen[4] = player5_wuerfelsumme;
wuerfelsummen[5] = player6_wuerfelsumme;
public int ermittleGewinner(JLabel[] w)
{
int temp;
int[] zahlen = new int[w.length];
for(int i=0; i<=zahlen.length; i++)
{
if(w[i].getText() == null)
{
zahlen[i] = 99999999;
}
else
{
zahlen[i] = Integer.parseInt(w[i].getText());
}
}
for(int i=1; i<zahlen.length; i++)
{
for(int j=0; j<zahlen.length-i; j++)
{
if(zahlen[j]>zahlen[j+1])
{
temp=zahlen[j];
zahlen[j]=zahlen[j+1];
zahlen[j+1]=temp;
}
}
}
for(int i=0; i<=zahlen.length; i++)
This is incorrect, as arrays are 0-indexed, meaning they reach from 0 to length-1.
Change it to
for(int i=0; i<zahlen.length; i++)
Interestingly enough, your other loops avoid this pitfall, although you will still have to be careful about the j+1 later on. Make sure that this can never be >= zahlen.length.
You could simply initialize j with 1 instead of 0 and then replace all occurences of j with j-1 and j+1 with j
change "i<=zahlen.length" in your for loop to "i < zahlen.length".
remember arrays are 0 indexed so you are trying to access an element one index outside of how large your array is with the "<=" method you are currently using
The second loop should start at i=0 instead of i=1. By using i=1, you are again going to try to access one element past the size of your array
ArrayIndexOutOfBounds expcetion comes when code tried to access an element of an array which is not present. In your code, since you are FOR looping one extra time for(int i=0; i<=zahlen.length; i++), you are getting this exception. Keep FOR loop as for(int i=0; i<zahlen.length; i++)
You have not to just check for zahlen[i] but also for w[i] because you are looping on length of zahlen and it may so happen that w is of lesser length then zahlen.

scope error in if statement in java program

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.

Transposing Values in Java 2D ArrayList

Good evening all,
I'm trying to write a method that creates and returns a 2D array whose elements in each location are the same as the elements in the mirror image location of the parameter array. Unfortunately, no matter what pair of numbers I enter into the method call I get an "out of bounds" error in my compiler. Below is my program. Tell me where I've gone wrong! Thanks!
public static int[][] transpose(int [][] a) {
int r = a.length;
int c = a[r].length;
int [][] t = new int[c][r];
for(int i = 0; i < r; ++i) {
for(int j = 0; j < c; ++j) {
t[j][i] = a[i][j];
}
}
return t;
}
}
Arrays in java are 0 based, change your assignment to c to :
int c = a[r - 1].length;
#Suraj is correct, however you must assume the 2D array is rectangular, in which case it is sightly more efficient to change line 3 to:
int c = a[0].length;
#Kris answer text is correct however code sample is wrong line.
Note this error is a reproduction of a broken "answer" posted in "Yahoo Answers": http://answers.yahoo.com/question/index?qid=20080121204551AAn62RO
Your problem lies in line two: a[r].length returns the number of columns, but arrays are indexed from 0. You should adjust accordingly:
int r = a.length - 1;

Categories

Resources