【发布时间】:2021-04-13 01:52:07
【问题描述】:
我有一个方法可以打开一个文件并将每一行转换为一个对象(它可以是 DVD 或 Livre,都在超类 Document 下),然后放入一个数组中。但出于某种原因,在这些行之后:
try {
tabChaineSafe[k] = tabChaine[k];
} catch (ArrayIndexOutOfBoundsException erreurarray) {
tabChaineSafe[k] = "Information indisponible.";
}
编译器只是跳过其余部分。因此,整个数组最终充满了空值。这是我使用调试器查看会发生什么的 gif 图像。
https://gyazo.com/a09c2b617ba94f12dce1165420d528dd
这是该方法的完整代码:
public static Document[] remplirTabDocs(Document[] tabDocs) {
String ligne = new String();
String[] tabChaine;
String[] tabChaineSafe = new String[6];
FileInputStream file = lectureFichier("doc.txt");
Scanner scan = new Scanner(file);
int j = 0; //compteur pour le tableau d'objets
while (scan.hasNext()) {
ligne = scan.nextLine();
tabChaine = ligne.split(",");
for (int i = 0; i < tabChaine.length; i++) { //nettoyage des
//espaces
tabChaine[i] = tabChaine[i].trim(); //tableau des infos
/*
** On va maintenant transférer ces String dans un nouveau
** String[] parce que parfois, il n'y a pas de description
** et cela peut causer des erreurs.
*/
for (int k = 0; k < tabChaineSafe.length; k++) {
try {
tabChaineSafe[k] = tabChaine[k];
} catch (ArrayIndexOutOfBoundsException erreurarray) {
tabChaineSafe[k] = "Information indisponible.";
}
//
if (tabChaineSafe[0].equalsIgnoreCase("Livre")) {
/*
** Étape 1 : Vérifier si un ouvrage de ce nom est
** déjà répertorié.
*/
boolean existant;
existant = checkExistants
(tabChaineSafe[1], tabDocs);
if (existant) {
int numDocExistant = lequelExistant
(tabChaineSafe[1]
, tabDocs);
tabDocs[numDocExistant].copiesDispo++;
} else {
Livre livre = new Livre(tabChaineSafe[0],
tabChaineSafe[1],
tabChaineSafe[2],
tabChaineSafe[3],
tabChaineSafe[4],
tabChaineSafe[5],
1);
}
} else if (tabChaineSafe[0].equalsIgnoreCase("DVD")) {
/*
** Étape 1 : Vérifier si un ouvrage de ce nom est
** déjà répertorié.
*/
boolean existant;
existant = checkExistants(tabChaineSafe[1],
tabDocs);
if (existant) {
int numDocExistant = lequelExistant
(tabChaineSafe[1]
, tabDocs);
tabDocs[numDocExistant].copiesDispo++;
} else {
try {
int nbDisquesInt = Integer.parseInt
(tabChaineSafe[3]);
DVD dvd = new DVD(tabChaineSafe[0],
tabChaineSafe[1],
tabChaineSafe[2],
nbDisquesInt, 1);
} catch (NumberFormatException nbfmtexc) {
/*
** Aucune instance n'est générée
*/
}
}
}
//
}
j++;
}
}
fermetureFichier(file);
return tabDocs;
}
我不知道为什么会这样。同样对于上下文,将 tabChaine 的值转移到 tabChaineSafe 是必要的,因为有时文档中的一行缺少信息,我想避免这种情况导致属性被分配为 null。
【问题讨论】:
-
如果
tabChaine.length小于tabChaineSafe的长度会怎样?你会得到一堆空值。如果tabChaine由于扫描仪输入的输入问题而从未填写过会怎样?您将拥有一个空值数组。通过将值打印到控制台来进行一些调试,以确定从扫描仪读取的内容,以及tabChaine是否实际上被填充了值。此外,您的调试器会这样跳过的原因是您的代码不满足以下 if 或 else if 语句。 -
这是我尝试 catch 的原因,当我检查调试器变量窗口时,tabChaine 和 tabChaineSafe 都可以正常工作
-
这里显然存在不满足
if和else if条件的问题,例如if ( tabChaineSafe[0].equalsIgnoreCase("Livre") ),tabChaineSafe[0] 是否永远等于“Livre”,显然不是如果我们使用您的调试器 gif。请编辑您的问题以包含更多信息,包括您放入扫描仪的一些示例值或我们可以测试的MCVE,或者编辑您的问题以在 try/catch 块之后显示调试器值。 -
编译器不会执行你的代码。他们编译它。要精确。不清楚你在问什么。
标签: java arrays methods compilation