简体   繁体   中英

Java - Read from .txt file into a Object

I have an Object Called Question. It has the following attributes:

  • String question, option1, option2, option3, answer

  • double difficulty

  • int category

I have a file called questions.txt which has the information regarding these attributes, attributes are separated by a comma. (1 Object per line)

eg

Carmine is a vivid shade of which colour?,Blue,Green,Yellow,Red,1,2

I want to read each line of the file creating an Object Question and adding it to an ArrayList called questionBank.

With the example mentioned above, this would be the result of the new Object created.

question = Carmine is a vivid shade of which colour?

option1 = Blue

option2 = Green

option3 = Yellow

answer = Red

difficulty = 1

category = 2

I have got the following code so far, but have no idea of how to extract each attribute between the commas so I can use it as an argument during Object instantiation.

Scanner input = new Scanner(new File("/Users/usaamahpatel/IdeaProjects/sdd_assignment/src/questions.txt"));
    input.useDelimiter(",");

    while (input.hasNext()) {
        System.out.println(input.next());
    }

This is the output I get from the above code:

Carmine is a vivid shade of which colour?
Blue
Green
Yellow
Red
1
2

As you can see It prints each item between the commas, how do I extract all attributes per line for one Object and so on?

I assume you have more than one line in the file, so more than one question, right ?

So then use as delimiter not , , but newline to read line by line (or use Files#readLines for that. Then you know each line represent one object. To retrieve the different attributes of the object you can split the line with , and fill the object

Assuming each Question you want is separated by a newline you could use input.nextLine().split(",") to get an array of Strings where each element is an attribute. You can then use Double.valueOf() and Integer.valueOf() to parse the difficulty and category to the proper types.

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