简体   繁体   中英

Assigning properties to an object in Java from a text file

I'm currently building a gamebook text based adventure program which will accept a certain format of txt file which looks like the one below.

Now this may all seem pretty simple however, I need to create Section objects in order for my game to work properly. As you can see above, the sections are often different sizes depending on how many possible choices they have to their appropriate story text. My section object has the declaration of

Section(String storytext, String choiceText, int choiceSections)

And I need to pull the appropriate details from this text file. I was reading through some forums and found an somewhat appropriate looking approach to the reading through the text file. The code was as follows which works in triplets, not necessarily good for me as my text files come in variable lengths. And obviously this is just an example of code, I would need to parse out both integers and strings.

Car[] car = new Car[length/3];

for (int i = 0; i < length/3; i ++) // 
{
    int startReading = Integer.parseInt(inputFile.readLine());
    int endReading = Integer.parseInt(inputFile.readLine());
    int liter = Integer.parseInt(inputFile.readLine());
    car[i] = new Car (startKm, endKm, litre);
}

This seems like it would work for me however, I need my loop to update dynamically based upon a few criteria. #1 > The number on the first line which is the total number of section objects which will be created. #2 > The number on the total choices line which will determine how many more lines the line reader needs to run through before stopping and creating the object. I'm quite lost on how to create a proper loop which will create my objects based on this criteria for these text files.

6 < Number of "sections" in the game

1 < Section number (1)

While making a peanut butter and jam sandwich one evening you discover that you've run out of strawberry jam. < Story text associated with the section

2 < Number of possible choices

5 < The choice below leads to this section

If you make do with grape jelly, click here. < This is one of the choices

4 < The choice below leads to this section

If you head out to the store to buy strawberry jam, click here. < This is one of the choices

2 < Section number (2)

You arrive home and begin making a fresh sandwich with your favourite condiment. You lovingly spread the peanut butter and the strawberry jam, salivating at the wonderful aroma. Unable to resist any longer, you take a bite. Utter bliss envelopes you, the perfect blend of flavours a cascade of awesomeness filling your consciousness. < Story text associated with this section

0 < Number of possible choices

3 < Section Number (3)

Your stomach immediately starts to hurt. Pain stabs at your abdomen and you double over, gasping for breath. The floor crashes up and darkness clouds your vision. < Story text associated with this section

0 < Number of possible choices

4 < Section Number (4)

You rush to the grocery store and look for your favourite brand of strawberry jam. You are surprised to find a new variety, fieldberry, on the shelf beside the familiar jar. < Story text associated with this section

2 < Number of possible choices

2 < The choice below leads to this section

If you buy the strawberry jam, click here. < This is one of the choices

6 < The choice below leads to this section

If you buy the new fieldberry jam, click here. < This is one of the choices

5 < Section Number (5)

You dig around in the fridge for a while and find the grape jelly you remembered was back there. It smells a bit funky, but you slather it onto your bread just the same, holding your breath a bit. < Story text associated with this section

2 < Number of possible choices

3 < The choice below leads to this section

If you eat the smelly sandwich, click here. < This is one of the choices

4 < The choice below leads to this section

If you toss it in the garbage and go out to buy jam, click here. < This is one of the choices

6 < Section Number (6)

You arrive home and begin making a fresh sandwich with your exciting new condiment. You lovingly spread the peanut butter and the fieldberry jam, salivating at the wonderful aroma. Unable to resist any longer, you take a bite. < Story text associated with this section

1 < Number of possible choices //do not know the choice here yet.

3 < Choice section you are led too, 3 represents winning so it finishes at this point.

This will do:

public class Main {

    public static void main(String[] args) throws IOException {
         try (BufferedReader br = new BufferedReader(new FileReader(
                "C:\\path\\to\\file"))) {
            String line = br.readLine().trim(); // may throw IOException
            int num_of_sections = Integer.parseInt(line);
            List<Section> sections = new ArrayList<>(num_of_sections);
            for (int j = 1; j <= num_of_sections; ++j) {
                line = _skip_empty(br);
                int section_number = Integer.parseInt(line);
                String section_text = _skip_empty(br);
                line = _skip_empty(br);
                int num_choices = Integer.parseInt(line);
                List<Choice> choices = new ArrayList<>(num_choices);
                for (int choice = 0; choice < num_choices; ++choice) {
                    line = _skip_empty(br);
                    int go_to_section = Integer.parseInt(line);
                    String choice_text = _skip_empty(br);
                    choices.add(new Choice(go_to_section, choice_text));
                }
                sections.add(new Section(section_number, section_text, choices));
            }
        }
    }

    private static class Section {
        private final int sectionNumber;
        private final String storyText;
        private final List<Choice> choices;

        Section(int sectionNumber, String storyText, List<Choice> choices) {
            this.sectionNumber = sectionNumber;
            this.storyText = storyText;
            this.choices = choices;
        }

        public String getStoryText() {
            return storyText;
        }

        public List<Choice> getChoices() {
            return choices;
        }

        public int getSectionNumber() {
            return sectionNumber;
        }
    }

    private static class Choice {
        private final int leadsToSection;
        private final String choiceText;

        Choice(int leadsToSection, String choiceText) {
            this.leadsToSection = leadsToSection;
            this.choiceText = choiceText;
        }

        public int getLeadsToSection() {
            return leadsToSection;
        }

        public String getChoiceText() {
            return choiceText;
        }
    }

    private static String _skip_empty(BufferedReader br) throws IOException {
        String line;
        do {
            line = br.readLine();
            if (line == null) return ""; // winning choice does that
            line = line.trim();
        } while (line.isEmpty());
        return line;
    }
}

As you see I changed your Section class to accept a list of choices - that's more appropriate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM