如何列出新元素?

时间:2016-10-02 12:19:54

标签: java list input elements

我想创建一个用户输入创建的元​​素列表。我可以直接将元素存储到列表中,还是必须创建引用?我找到了如何制作预制变量的列表,但我想用用户输入创建te变量。

我的项目的目标是存储数据集并在以后调用它们。 首先,我理解列表的概念。因此,我不认为此时复制代码很有用。

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;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以尝试添加此代码:

ArrayList<String> items = new ArrayList<String>();

while (!userInput.equals("exit")){
   items.add(userInput.next());
}

答案 1 :(得分:0)

希望这有帮助

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;
}

}