0

I have a question about auto input data from txt file into array. I have this file txt below and I want to take input 2 array like Doctor and Pet. Doctor: name and specializaion private ArrayList arrDoctor = new ArrayList<>(); Pet: name, type, size, weight, age,doctor. private ArrayList arrPet = new ArrayList<>();

This is my file.txt.

doctors
name joao
specialisation cat
name maria
specialisation dog
pets
name lara
type cat
size small
weight 4.0
age 5
doctor joao
name biro
type dog
size large
weight 15.0
age 12
doctor maria
name benny
type cat
size large
weight 7.0
age 10
doctor none

1 Answer 1

1

You would need to read file for example like this:

try {
      File file = new File("PATH/TO/FILE/filename.txt");
      Scanner myReader = new Scanner(file);
      while (myReader.hasNextLine()) {
        String line = myReader.nextLine(); // this will be your single line in a file
        someLogicHere(line);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      // handle file not found
    }

After a line is parsed into program you would need some logic to determine if this is a doctor or a pet and create objects inside code.

This logic would look soomething like this :

String firstLine = "name joao";
String secondLine = "specialisation cat";
String name = firstLine.replace("name ", ""); // get rid of this name prefix
String specialisation = secondLine.replace("specialisation ", ""); // get rid of this specialisation prefix
Doctor doctor = new Doctor(name, specialisation);

I would strongly suggest to split doctors and pets into different files to make it easier for you. Addicionally what would make it even easier for you to have a doctor and pet writen one line per each not to have to parse to or more lines to create single object. Ex name joao specialisation cat

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.