简体   繁体   中英

How to assign the value to array of object correctly?

I don't know why after I'm running the code, array scoreMatrix always put the last assignment to the whole array.

        String input, seq="ACGT";
        PairScore[] scoreMatrix = new PairScore[16];
        for(int x = 0; x<16 ; x++){
            scoreMatrix[x] = new PairScore();
        }
        Scanner user_input = new Scanner( System.in );
        for(int i = 0; i <4;i++){
            input=user_input.nextLine();
            String[] inputSplite = input.split("\\s+");
            for(int j=0; j<4;j++){
                scoreTable[i][j] = Integer.parseInt(inputSplite[j]); 
            }
        }
        for(int x = 0; x<4 ; x++){
            for(int y=0; y<4; y++){
                scoreMatrix[x*4 +y].fString = Character.toString(seq.charAt(x));
                scoreMatrix[x*4 +y].sString = Character.toString(seq.charAt(y));
                scoreMatrix[x*4 +y].score = scoreTable[x][y];
            }
        }// Fix the score pair problems;
        for(int x1 = 0; x1<4 ; x1++){
            for(int y1=0; y1<4; y1++){
                System.out.println(scoreMatrix[x1*4 +y1].fString+scoreMatrix[x1*4 +y1].sString+scoreMatrix[x1*4 +y1].score);
            }
        }

Here is the code for the class PairScore

public class PairScore {
public static String fString;
public static String sString;
public static int score;

}

When I input

1 -1 -1 -1
-1 1 -1 -1
-1 -1 1 -1
-1 -1 -1 1

I got the following result:

TT1TT1TT1TT1.....TT1

but I expect to get the below result from the code:

AA1AC-1AG-1AT-1CA-1CC1...TT1

Why does it take the value TT1 and assign it to the rest of the array?

Make sure the members of PairScore ( fString , sString and score ) are not static.

If they are static, all instances of the PairScore class will share a single value for these three members, so you'll only see the last value that was assigned to those variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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