简体   繁体   English

即使在使用全局静态数组后,该数组的值也在Java中更改。 如何克服呢?

[英]Even after using a global static array my values of the array are changing in java. How to overcome it?

In this code I am having some problem as I have marked using a loop which is printing some values. 在这段代码中,我遇到了一些问题,因为我使用打印一些值的循环进行了标记。 I am storing them in an array as mentioned and am trying to print the values in another function. 我如上所述将它们存储在数组中,并尝试在另一个函数中打印值。 But even after using the global array the value of the array is changing. 但是,即使在使用全局数组之后,该数组的值仍在变化。

I am not able to figure out the problem. 我无法解决问题。 Please help me out. 请帮帮我。

import java.io.*;
import java.util.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

// Java program to print all permutations of a
// given string.
public class test3
{

    static int[] val = new int[100]    ;            //array declaration as global


    public static void main(String[] args)
    {

        System.out.println("An incremented value");
        for(int i=2;i<=2;i++) {
            String p="";
            for(int j=0;j<=i;j++) {
                for(int m=0;m<j;m++) {
                    p=p+"&";
                        }
                for(int m=0;m<i-j;m++) {
                    p=p+"|";
                        }
                 printAllPermutations(p);
                p="";
            }
        }

         System.out.println();

    for(int xy=0;xy<32;xy++)
        System.out.print("["+xy+"]"+"="+val[xy]+"   ");      //trying to print the array
    }


    static void print(char[] temp) {

        String a="";
        System.out.println();
      for (int i = 0; i < temp.length; i++)
      { System.out.print(temp[i]);
            a=a+temp[i];}

      System.out.print(" "+"opr:"+temp.length+"   ");
      final int N = temp.length+1;  

      /*===================CODE PROBLEM PART START=======================*/


      for (int i = 0; i < (1 << N); i++) {                          
        // System.out.println(zeroPad(Integer.toBinaryString(i), N));
         String b=zeroPad(Integer.toBinaryString(i), N)+"";
        // System.out.println("a:  "+a+"  b:"+b);
         char[] arrayA = b.toCharArray();
         char[] arrayB = a.toCharArray();
         StringBuilder sb = new StringBuilder();

         int ii = 0;
         while( ii < arrayA.length && ii < arrayB.length){
             sb.append(arrayA[ii]).append(arrayB[ii]);
             ++ii;
         }

         for(int j = ii; j < arrayA.length; ++j){
             sb.append(arrayA[j]);
         }

         for(int j = ii; j < arrayB.length; ++j){
             sb.append(arrayB[j]);
         }

         //System.out.println(sb.toString());
         try {
            ScriptEngineManager sem = new ScriptEngineManager();
            ScriptEngine se = sem.getEngineByName("JavaScript");
            String myExpression = sb.toString();
           // System.out.print(se.eval(myExpression));

            val[i]=(int)(se.eval(myExpression));   //inserting array value
            System.out.print(val[i]);               //NEED TO HAVE THESE VALUES IN THE 1-D ARRAY


           // System.out.print(val[i]);

         } catch (ScriptException e) {
             System.out.println("Invalid Expression");
             e.printStackTrace();}
      }  
      /*===================CODE PROBLEM PART END========================*/
     //

    }




    //unchangable = rest of the function
    static int factorial(int n) {
      int f = 1;
      for (int i = 1; i <= n; i++)
        f = f * i;
      return f;
    }

    static int calculateTotal(char[] temp, int n) {
      int f = factorial(n);

      // Building HashMap to store frequencies of 
      // all characters.
      HashMap<Character, Integer> hm = 
                       new HashMap<Character, Integer>();
      for (int i = 0; i < temp.length; i++) {
        if (hm.containsKey(temp[i]))
          hm.put(temp[i], hm.get(temp[i]) + 1);
        else
          hm.put(temp[i], 1);
      }

      // Traversing hashmap and finding duplicate elements.
      for (Map.Entry e : hm.entrySet()) {
        Integer x = (Integer)e.getValue();
        if (x > 1) {
          int temp5 = factorial(x);
          f = f / temp5;
        }
      }
      return f;
    }

    static void nextPermutation(char[] temp) {

      // Start traversing from the end and
      // find position 'i-1' of the first character 
      // which is greater than its  successor. 
      int i;
      for (i = temp.length - 1; i > 0; i--)
        if (temp[i] > temp[i - 1])
          break;

      // Finding smallest character after 'i-1' and
      // greater than temp[i-1]
      int min = i;
      int j, x = temp[i - 1];
      for (j = i + 1; j < temp.length; j++)
        if ((temp[j] < temp[min]) && (temp[j] > x))
          min = j;

      // Swapping the above found characters.
      char temp_to_swap;
      temp_to_swap = temp[i - 1];
      temp[i - 1] = temp[min];
      temp[min] = temp_to_swap;

      // Sort all digits from position next to 'i-1'
      // to end of the string.
      Arrays.sort(temp, i, temp.length);

      // Print the String
      print(temp);
    }

    static void printAllPermutations(String s) {

      // Sorting String
      char temp[] = s.toCharArray();
      Arrays.sort(temp);

      // Print first permutation
      print(temp);

      // Finding the total permutations
      int total = calculateTotal(temp, temp.length);
      for (int i = 1; i < total; i++)
        nextPermutation(temp);
    }

    static String zero(int L) {                                      
          return (L <= 0 ? "" : String.format("%0" + L + "d", 0));      
       }                                                               
    static String zeroPad(String s, int L) {                        
          return zero(L - s.length()) + s;                              
       } 

}

The output that I am getting is 我得到的输出是

 An incremented value

      || opr:2   01111111     //WANT TO STORE THESE 32 VALUES IN 1 D ARRAY 
      &| opr:2   01010111      // AND PRINT THEM OUT 
      |& opr:2   00011111     
      && opr:2   00000001      

[0]=0   [1]=0   [2]=0   [3]=0   [4]=0   [5]=0   [6]=0   [7]=1   [8]=0   [9]=0   [10]=0   [11]=0   [12]=0   [13]=0   [14]=0   [15]=0   [16]=0   [17]=0   [18]=0   [19]=0   [20]=0   [21]=0   [22]=0   [23]=0   [24]=0   [25]=0   [26]=0   [27]=0   [28]=0   [29]=0   [30]=0   [31]=0 

what I need to do is to store those 32 values in 1 D array for further operation but while doing it all the array values displays 0 only except [7]. 我需要做的是将这32个值存储在1 D数组中以进行进一步的操作,但是在执行此操作时,除[7]之外,所有数组值仅显示0。 I dont know whats going on here. 我不知道这是怎么回事。

Reference types are not bound to local scopes, just because your array is static to the class it does not mean that changing the values in one function will not change the values in the actual array. 引用类型不受本地范围的约束,仅因为您的数组对于该类而言是静态的,并不意味着更改一个函数中的值不会更改实际数组中的值。 The reference to your array as a parameter will be a copy, but the reference is still "pointing" on an actual object, which is not a copy bound to your local scope. 对数组的引用作为参数将是一个副本,但该引用仍是“指向”实际对象,而不是绑定到本地作用域的副本。

If you want to save two different states of the array, you will have to save them yourself. 如果要保存阵列的两个不同状态,则必须自己保存它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM