давайте пройдемся по ней шаг за шагом.
Сначала вы запускаете программу с помощью main
метода:
public static void main(String[] args){
// execute this code here
}
Этот метод вы можете добавить в любой класс, который вам нравится. Я бы предложил поместить его в класс, который вы будете использовать для «управления» потоком вашей программы:
public class MyJarProgram{
public static void main(String[] args){
}
}
Теперь, чтобы избавиться от всей этой static
и нестатической путаницы, давайте продолжим »Объекты »(экземпляры классов). Это означает, что main
метод - единственная статичная вещь, которая вам понадобится.
Теперь вы хотите начать строить своих игроков, флягу (я не знаю, что это такое, но неважно :), позиции и все остальное. так что вы можете начать спрашивать у пользователя имя игрока:
public static void main(String[] args){
System.out.print("Please enter the player's name");
String playerName = Global.keyboard.nextLine(); // I guess this method works like this, so your variable playerName should now contain the user's input
// now you can instantiate your player object
Player player = new Player(playerName); // here we need a constructor of the class player that takes the name.
}
Итак, теперь вам нужно создать класс Player
и присвоить ему конструктор с именем
public class Player{
private String name; // make all variables in your classes non-static and private to be on the save-side
public Player(String name){
this.name = name; // you take the parameter name and set the private member variable name to the same value
}
// since your variable name is private to the class player you might want to add some standard getter and setter methods like this:
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
Как вы это сделали с name
плеера, вы можете сделать это и с position
. Дайте классу Player
еще одну переменную-член position
и добавьте необходимый код в конструктор (и, возможно, также метод получения и установки).
Тогда ваш основной метод может выглядеть следующим образом:
public static void main(String[] args){
System.out.print("Please enter the player's name");
String playerName = Global.keyboard.nextLine();
Player player = new Player(playerName, 0); // creates the player with his name and position.
System.out.println("Player :"+player.getName()+" is on position "+player.getPosition()); // and that's how you can access the players attributes with your getters and setters
}
Хотя я предполагаю, что вы можете задать игроку позицию по умолчанию 0, и в этом случае вы не передаете позицию в конструкторе, а устанавливаете позицию в 0:
public Player(String name){
this.name = name; // takes the parameter to init the name
this.position = 0; // will initialize the position by default with 0
}
Ну, янадеюсь, это поможет вам лучше понять конструкторы, классы и прочее. Удачи!