"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1" -
this question has answer here:
i've got simple question i've got complete tomorrow. code compiles , runs exception error. sorta kinda new java , have feeling related multidimensional array.
package question12; import java.security.securerandom; import java.util.scanner; public class question12 { scanner sc = new scanner(system.in); string first_name, last_name, id, seat_no; char seatch; string[][] passengerlist = new string[1][4]; void setfname() { system.out.printf("passenger first name: "); first_name = sc.nextline(); } void setlname() { system.out.printf("passenger last name: "); last_name = sc.nextline(); } void setid() { system.out.printf("passenger id: "); id = sc.nextline(); } void setseatnumber () { string ticket, stringrandnum; string alfabet = "abcdefghijklmnopqrstuvwxyz"; int seatcharnum, seatintnum; securerandom randomn = new securerandom(); seatintnum = randomn.nextint(120); seatcharnum = randomn.nextint(7); seatch = alfabet.charat(seatcharnum); seat_no = "" + seatintnum; } void generateticket() { (int = 0; < 39; i++) { if (i == 19) { system.out.printf("air kzn"); } else system.out.print('*'); } system.out.println(""); system.out.printf("*you seated in seat number: %s%s%n", seatch, seat_no); system.out.printf("*passenger name: %s\n", first_name); system.out.printf("*passenger surname: %s%n", last_name); system.out.printf("*passenger id: %s%n", id); (int = 0; < 39; i++) { if (i == 19) { system.out.printf("air kzn"); } system.out.print('*'); } system.out.println(""); } void storevalues() { passengerlist[0][0] = first_name; passengerlist[0][1] = last_name; passengerlist[0][2] = id; passengerlist[0][3] = seat_no; } void printpassengerlist() { system.out.printf("passenger name passenger surname passenger id seat number\n"); (int = 0; < 40; a++) system.out.print('-'); (int c = 0; c < passengerlist.length; c++) (int d = 0; d < passengerlist[d].length; d++) system.out.print(passengerlist[d][c]); } public static void main(string[] args) { question12 q12 = new question12(); q12.setfname(); q12.setlname(); q12.setid(); q12.setseatnumber(); q12.generateticket(); q12.storevalues(); q12.printpassengerlist(); } }
you have:
for (int c = 0; c < passengerlist.length; c++) (int d = 0; d < passengerlist[d].length; d++) system.out.print(passengerlist[d][c]);
this give error because of 2 reasons:
your inner loop should have
passengerlist[c].length
instead ofpassengerlist[d].length
.your printout should
passengerlist[c][d]
instead ofpassengerlist[d][c}
.
change this:
for (int c = 0; c < passengerlist.length; c++) (int d = 0; d < passengerlist[c].length; d++) system.out.print(passengerlist[c][d]);
Comments
Post a Comment