In: Computer Science
/**
* Loads a list of items from the given file. Each line is in the
format
* <item type>~<item data>. The createFromString()
methods in the item
* classes will be used to parse the item data.
* @param filename the filename
* @return the list of items
* @throws IOException if the file can't be opened
*/
public static List<Item> loadItems(String filename) throws
IOException {
List<Item> items = new ArrayList<>();
Scanner inPut = new Scanner(new FileReader(filename));
while(inPut.hasNextLine()) {
String line =
inPut.nextLine();
String [] tokens
= line.split(":");
String type =
tokens[0];
String data =
tokens[1];
items.add(type,data);
}
return items;
}
}
can you please check this line " items.add(type,data);" . I am having problem with it
Note:
1.)We can't write List generic type as class name.
2.)We can't add two arguments ex:add(data,type)
we can add only one item by uisng add() Method, ex:add(data). If you want add multiple items then you can use addAll() method
Code:
package assignment;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Item {
public static List<String> loadItems(String
filename) throws IOException {
List<String> items = new
ArrayList<>();
Scanner inPut = new Scanner(new
FileReader(filename));
while(inPut.hasNextLine()) {
String line =
inPut.nextLine();
String [] tokens =
line.split(":");
String type = tokens[0];
String data = tokens[1];
items.add(type);
items.add(data);
}
return items;
}
public static void main(String[] args) throws
IOException {
List
list=loadItems("abc.file");
list.forEach(System.out::println);
}
}
Note:****I hope your happy with my answer***If you have any doubts please comment me****Thank you.....