我是新来的爪哇人希望你们都做得很好。
因此,我试图从文本文件中提取值,并将其放入名为tableauForfaits的数组中,但是我被阻止了,有人可以帮助我查看我的错误所在,因为当我试图拆分它时,它不起作用。
私有静态最终字符串FIC_FORFAITS = "Forfaits.txt";
// Déclaration des variables
private static Forfait tableauForfaits[] = new Forfait[6];
* Read data from different packages (id | description | price)
* in the "Forfaits.txt" file. The first line in this file is the
* description of other lines and it should be ignored when
* reading. The other lines of this file are each composed of the identifier,
* of the description, and the price separated from each other by a vertical bar.
* Each of these lines must be read and cut to create an object of type
* Package, and this item should be added in the package table above
* defined (see Forfaits.txt file for more details)
*
public static void lireFichierForfaits() throws IOException,FileNotFoundException {
try (BufferedReader reader = new BufferedReader (new FileReader(FIC_FORFAITS))) {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
tableauForfaits = line.split("\\|");
for (String part : tableauForfaits) {
System.out.println(part);
}
System.out.println();
}
reader.close();
}
}
/福费特班:
private String identifiant;
private String description;
private float prix;
public Forfait (String identifiant, String description, float prix) {
this.identifiant = identifiant;
this.description = description;
this.prix = prix;
}
public String getIdentifiant () {
return identifiant;
}
public void setIdentifiant (String identifiant) {
this.identifiant = identifiant;
}
public String getDescription () {
return description;
}
public void setDescription (String description) {
this.description = description;
}
public float getPrix () {
return prix;
}
public void setPrix (float prix) {
this.prix = prix;
}
发布于 2022-04-13 17:49:28
这是:
tableauForfaits = line.split("\\|");
不能工作,因为String#split(...)
返回一个字符串数组,并且您试图将它强制到一个不同类型的数组,一个Forfait对象中。
相反,这一行应该是
String[] tokens = line.split("\\|");
这将希望将行从文本文件拆分为单独的小字符串标记,这些标记可用于帮助您使用令牌创建单个Forfait对象。如何创建对象完全取决于这个类的结构(这个类目前我们无法看到),但是您可能需要使用获得的字符串标记调用它的构造函数,然后将创建的Forfaitobject放到tableauForfaits数组中,可能类似于,
Forfait forfait = new Forfait(token[0], token[1].....);
请注意,在执行此操作之前,可能需要将数字令牌字符串解析为数值,如
Forfait forfait = new Forfait(Integer.parseInt(token[0]), token[1], .....);
同样,不可能确定地说,因为我们目前无法看到Forfait类或文本文件。
您还需要在while循环之前创建一个int索引变量,在while循环中增加它,并将其用作tableauForfaits数组的索引,以帮助您决定将新创建的对象放入数组的哪一行。
https://stackoverflow.com/questions/71865507
复制