Joeri Venekamp Joeri Venekamp - 2 months ago 8
Java Question

How do I make a list of new elements?

I want to make a list of elements create with user input. Can I directly store an element into a list, or do I have to create a reference? I found how to make a list of premade variables, but I want to create te variables with user input.

The goal of my project is to store dataset and recall them at a later moment.
First I understand the concept of lists. Therefore I don't think its useful to copy my code at this moment.

import java.util.*;

public class Database {

public Database () {

}

public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);

public static void main(String[] args) {

System.out.println("Add a new spawnpoint.\n");

System.out.println("State the name of this spawnpoint: ");


Spawnpoints Sp1 = new Spawnpoints(getSpawnName());

System.out.println("Name: " + Sp1.getSpawnName());
System.out.println("Location: " + Sp1.getLocation());
System.out.println("Pokemon: " + Sp1.getPokemon());
System.out.println("Spawntime: " + Sp1.getSpawntime());

System.out.println("The pokemon is currently spawned: " + Sp1.isSpawned());

numberOfSpawnpoints++;

}

public static String spawnName;

public static String getSpawnName() {

spawnName = userInput.next();
return spawnName;
}

public void setSpawnName(String spawnName) {

Database.spawnName = spawnName;
}
}

Answer

Hope this helps

import java.util.*; 

public class Database {

public Database () {

}

public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);

public static void main(String[] args) {

    System.out.println("Add a new spawnpoint.\n");

    System.out.println("State the name of this spawnpoint: ");
    ArrayList<Spawnpoints> SPlist = new ArrayList<Spawnpoints>();

    SPlist.add(new Spawnpoints(getSpawnName())); 
    // the above line will create an object of Spawnpoints and store it in  list

    System.out.println("Name: " + SPlist.get[0].getSpawnName());
    System.out.println("Location: " + SPlist.get[0].getLocation());
    System.out.println("Pokemon: " + SPlist.get[0].getPokemon());
    System.out.println("Spawntime: " + SPlist.get[0].getSpawntime()); 

    System.out.println("The pokemon is currently spawned: " + SPlist.get[0].isSpawned());

    numberOfSpawnpoints++;

}

public static String spawnName;

public static String getSpawnName() {

    spawnName = userInput.next();
    return spawnName;
}

public void setSpawnName(String spawnName) {

    Database.spawnName = spawnName;
}

}