0

So i first declare this object of a class:

static enterprise[] en = new enterprise[10];

Then, inside main:

for(int i=0;i<=9;i++){
    System.out.println("Insert name of the " + (i+1) + "ª enterprise");
    en[i] = new enterprise(i);
    Scanner scanner = new Scanner(System.in);
    en[i].setName(scanner.next());
    System.out.println(en[i].Name);
    }

And then, in another method of the same class:

for(int i = 0; i<=9;i++){
    System.out.println(en[i].index + "- " + en[i].Name);
}

So if at first I inserted on the first enterprise A, second B, C,D,E,F,G,H,I,J.. I should get as an output 1 A 2 B etc, but I get 9 J ten times. why does this happen?

Edit: here is the enterprise class: http://pastebin.com/gUCWRRgK

1
  • static fields are shared among instances, so remove the static modifier from those fields you want to have independent values per instance. See here, the relevant part of the Sun Java Tutorials. Commented Aug 2, 2012 at 23:25

2 Answers 2

1

It's because your fields are declared static.

public class enterprise {
    static String Name;
    static int index;

When a field is static it means that variable is associated with the class. Static variables cannot have different values for each instance.

It should be this:

public class enterprise {
    String Name;
    int index;
Sign up to request clarification or add additional context in comments.

7 Comments

Hmm, but now I get error on eclipse on another class named player, I have a total of 4 classes, player, enterprise, enemy and main. Eclipse says that amount, name and value must be static
Here is the exact error: Cannot make a static reference to the non-static field enterprise.Name And here the code: pastebin.com/YHqNZdWZ
@zyngawow: Oh wait, you don't actually have an instance there which is why you get the error. In that case you do need those two fields to be static (but only those two). But this code smells bad. Those fields should probably should be instance variables on your player instead, assuming it's some sort of count of the total value the player owns.
There is only one player instance, but multiple enemies and multiple enterprises. Could you explain it a bit better?
@zyngawow: If total is the total for your player, then you should make it an instance variable on your player. If it's a total for your entire universe then you could make a new class called Universe and put the field there. It's a very bad idea to have public static non-final fields. They're Java's equivalent of global variables, and global variables are usually considered to be a Very Bad Thing.
|
0

That's because you made your variables static. Remove the static keywords and it'll work. static does not work in Java like it does in C.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.