-3

I am really stumped with my code:

I have a static class:

static class Test
{
           static b;
           static c;
}

and in my main class, I have initialized an array of static Test.

Test[] AB = new Test[5];

I then fill the array with:

for(int a=0; a<AB.length; a++)
{
int C = new int();
int D = new int();
C = get user input here....
D = get user input here...
AB[a].c = C;
AB[a].b = D;
}

When I output the array, all my values are the last values inputted. Basically, if user last inputted C = 5, D = 4. All the values from AB[0] - AB[4] for c and b are 5 and 4.

I'm really stumped.

Can anyone help me with this issue?

Thanks!

  • Static variables have the same value across all instances of a class. – Marc Baumbach Aug 26 '15 at 05:39
  • 2
    @Codebender Seems like pseudo logic to me. Not actual code. – Suresh Atta Aug 26 '15 at 05:41
  • 1
    @Suresh, Ya.. that's right... – Codebender Aug 26 '15 at 05:42
  • how are you accessing static classes. you can't declare top level static classes – SacJn Aug 26 '15 at 05:42
  • So many errors in that code, e.g. `new Test[5]` does *not* allocate 5 objects of type `Test`. It only allocates an *array* of 5 *references*, that are all `null`. --- `new int()` is meaningless in Java. --- `static b` has no type. – Andreas Aug 26 '15 at 05:44
  • This code doesn't compile. – user207421 Aug 26 '15 at 05:45
  • @Andreas Ironically, being static members makes `AB[a].c = ..` (where `AB[a]` evaluates to null, and the expression is of type Test) compile fine .. and not throw a NPE when executed. The other problems remain, however. – user2864740 Aug 26 '15 at 05:47
  • 2
    [What does the 'static' keyword do in a class?](http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class) – Naman Gala Aug 26 '15 at 05:48
  • @user2864740 Wow, you are so right. Dang! So *this* is what code obfuscation looks like. Of course, I never actually *said* it would throw NPE. (Saved by the bell) – Andreas Aug 26 '15 at 05:49
  • Ok, ok, here is a constructive comment: Please post questions that are *Minimal, Complete, and Verifiable*. See http://stackoverflow.com/help/mcve – Andreas Aug 26 '15 at 05:52

1 Answers1

2

static values are shared across all the instance. You need to take instance members. Not static.

Create a normal class and take instance members, then you can have instance specific values of them.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307