Search code examples
javaarraysstructure

Java array values gets overwritten


I am new to Java and this is a very basic question. However I struggle to find a solution, so hopefully someone could give me some pointers.

I am trying to fill values into an array "addedPlayer". However, every time I run the AddPlayer() method it is initialiezed to zero again.

How can I structure this in a better way?

public class DemoApplication implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    public void AddPlayer() {
        int[] addedPlayer;

        addedPlayer = new int[500];

        System.out.println(" *** Add new player *** ");
        System.out.println("Name:");
        String name = System.console().readLine();
        System.out.println("Age:");
        int age = Integer.parseInt(System.console().readLine());
        System.out.println("JNUM:");
        int jnum = Integer.parseInt(System.console().readLine());

        player p = new player();
        p.SetAge(age);
        p.SetName(name);
        p.SetJnum(jnum);

        System.out.println(addedPlayer[0]);
        for (int j = 0; j < addedPlayer.length; j++) {
            if (addedPlayer[j] != 0) {
            } else {
                addedPlayer[j] = p.GetAge();
                System.out.println(addedPlayer[j]);
                System.out.println(j);
                break;
            }
        }
    }

    public void EditPlayer() {
        //empty
    }

    public void ListPlayer() {
        //empty
    }

    @Override
    public void run(String... args) throws Exception {
        while (true) {
            System.out.println(" *** MENY *** ");
            System.out.println(" 1. Add player ");
            System.out.println(" 2. Edit player ");//ÖKurs
            System.out.println(" 3. List player ");
            System.out.println(" 100. Exit ");
            System.out.println("Ange val");
            int sel = Integer.parseInt(System.console().readLine());

            if (sel == 100) break;
            if (sel == 1) AddPlayer();
            if (sel == 2) EditPlayer();
            if (sel == 3) AddPlayer();
        }
    }
}

Solution

  • Each time you run AddPlayer(), it creates a new player from scratch. If you want to keep your modifications to a bare minimum, you must put it outside of the method and make it a property for your class like List<int[]> addedPlayers = new ArrayList<int[]>(); and you can add this line AddPlayer to add it in a list addedPlayers.add(addedPlayer). Otherwise, if you want a more cleaner code, you should add more classes than only one main class. To improve your code, you can see @g.momo's answer.