Home > OS >  I wanted to create a java Object by reading a text file
I wanted to create a java Object by reading a text file

Time:12-03

The text file contains the following data :

Rock
12
10
0

I want to use this data and add as properties to the Object. The Object Name is the player and the properties are:

  • name
  • maximum_health
  • current_health
  • no_of_wins

So when the object is created the player.name is "Rock", player.maximum_health is 12, player.current_health is 10 and player.no_of_wins is 0.

CodePudding user response:

You can use Regex named group to get them or use split by space

public static void main(String... args) {
    String text = "Rock 12 10 0";
    Pattern pattern = Pattern.compile("([a-zA-Z0-9] ) ([0-9] ) ([0-9] ) ([0-9] )");
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        String name = matcher.group(1);
        String maximum_health = matcher.group(2);
        String current_health = matcher.group(3);
        String no_of_wins = matcher.group(4);
        Player player = new Player(name, maximum_health, current_health, no_of_wins);
    }
}
  • Related