I'm trying to display the names from my 2d array.
public class last{
static void afficherMINU(String[][]nomPre){
for(int i=0;i<nomPre.length;i++){
for(int j=0;j<nomPre.length;j++){
System.out.printf(nomPre[i][j]+"\n");
}
}
}
public static void main(String []args){
String[]codePerm={"VILC15539307","NDIJ19129406","LANM29089409","JEAJ03108909","TOUS17529409","TRED01039200","AUCM28579305"};
String[][]nomPre={{"VILLENEUVE-ASSE","CINDY"},{"NDIAYE YEND","JEAN-LOUIS RUDY"},{"LANDRY-VIGNEAULT GARCIA","MARCEL"},{"JEAN-BAPTISTE","JOSEPH-RAYMOND MARC"},{"TOUCHETTE","SOPHIE ANNE-MARIE"},
{"TREMBLAY","DENIS MARC-ANDRE PIERRE"},{"AUCLAIR-JULIEN","MARIE-ISABELLE"}};
afficherMINU(nomPre);
}
}
The first information from "String[][]nomPre"
in the double array is the last name followed by their name. For example when i display the array it should look like
VILLENEUVE-ASSE, CINDY
NDIAYE YEND, JEAN-LOUIS RUDY
and so on. But my code keeps printing:
VILLENEUVE-ASSE
CINDY
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at last.afficherMINU(last.java:6)
at last.main(last.java:16)
Your inner loop has the wrong termination bound. The value of nomPre.length
is 7 (if I counted correctly), but the inner loop needs to stop after the length of nomPre[i]
, since that's what's indexed by j
. Use this instead:
for(int j=0;j<nomPre[i].length;j++){ // NOT nomPre.length
System.out.printf(nomPre[i][j]+"\n");
}
Better yet, capture the i
th row in the outer loop:
for(int i=0;i<nomPre.length;i++){
String[] row = nomPre[i];
for(int j=0;j<row.length;j++){
System.out.printf(row[j]+"\n");
}
}
In afficherMINU
, this
for(int j=0;j<nomPre.length;j++) {
should be
for(int j=0;j<nomPre[i].length;j++) {
Or use, Arrays.deepToString(Object[])
like
System.out.println(Arrays.deepToString(nomPre));
Or use a for-each loop,
for(String[] arr : nomPre){
System.out.println(Arrays.toString(arr));
}
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.