Forum Stats

  • 3,838,711 Users
  • 2,262,394 Discussions
  • 7,900,739 Comments

Discussions

Why am I getting the wrong sum in java?

420ddffd-5fa8-431b-97e5-ca054c1694e5
edited Apr 25, 2019 3:18AM in Java Programming

Netbeans is giving me the wrong sum.

int[] x=new int[2];

int[] y=new int[2];

Data data=new Data();

Random rand=new Random();

int r1,r2;//Results of random numbers.

r1=rand.nextInt(2);

System.out.println("First random number is: "+r1);

r2=rand.nextInt(2);

System.out.println("Second random number is: "+r2);

if(r1==0){

x=data.a();

}else if(r1==1){

x=data.b();

}

if(r2==0){

y=data.a();

}else if(r2==1){

y=data.b();

}

int result=x[0]+y[0];

System.out.println("The sum is: "+result);

//I get the wrong sum when I get '1' and '0'.

This is a the java class of the data.

int[] x=new int[2];

public int[] a(){

x[0]=300;

x[1]=3;

return x;

}

public int[] b(){

x[0]=250;

x[1]=2;

return x;

}

I don´t know why it is giving me the wrong answer. Thanks in advance.

Answers

  • rpc1
    rpc1 Member Posts: 1,503
    edited Apr 25, 2019 3:18AM

    What did you mean by right answer ? It returns answer according your code:

    functions a() and  b() returns the same object x , therefore all you array variables work with one object