'Create a function with a class Player with values "username" set to input, "size" to 50, "x" and "y" to 0

Trying to create a function with a class Player with values "username" set to input and the rest set to numbers. Searched a few websites but the answers weren't really helpful

Current code:

Player createPlayer(String un) {
    class Player{
    String useruname = un;
    int size = 50;
    float x = 0;
    float y = 0;
    }
    return class Player;
}

Error: illegal start of experssion (line 7)



Solution 1:[1]

In short, the class should probably look something like this:

public class Player {
    private String username;
    private int size;
    private float x;
    private float y;

    public Player(String un) {
        username = un;
        size = 50;
        x = 0;
        y = 0;
    }
}

First of all, when you're creating a new class in Java, you need to make sure it's in its own file, named according to the name of the class (for example, this code would be in a file called Player.java. As for the code itself, you'll notice that I first declared the variables username, size, x, and y without assigning them values. In Java, it's common to declare a class's instance variables like this, and assign them values later (although it's up to personal preference).

You'll also notice that I didn't include a function that returns a Player instance. This is because, in Java, you can use a constructor instead. The constructor for this Player class is the method beginning with public Player(String un). Constructors look very similar to regular methods, but instead of starting with a return type and a name, they simply start with the name of the class. The constructor of a class is called whenever a new instance of that class is created, so it's perfect for setting an instance's initial values. In this case, the Player constructor sets the values of size, x, and y to preset integer values. Since you can pass arguments to constructors, it also sets the value of username to the un argument, which can be specified every time a new player is created.

To create a new instance of the player, it's just like creating a new instance of any other class, except you need to pass in all of the arguments that you specified in the constructor method. For example,

Player myPlayer = new Player("MyUsername");

will create a new instance of the Player class called myPlayer, which has the username "MyUsername".

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sdk3n