java - 2D arrays issue -
i have problem 2d array. want print 20 lines a..j letters on each line. can't print row 9, 19, 20 following code. also, code prints 19x9 lines of null. ideas?! thanks. that's code:
public class cinema_seats { string[][] seats = new string[20][10]; for(int row=0; row<seats.length-1; row++){ for(int column=0; column<seats[row].length-1; column++){ if(row!=0) system.out.print("row" + row + " " + 'a' + " " + 'b' + " " + 'c' + " " + 'd' + " " + 'e' + " " + 'f' + " " + 'g' + " " + 'h' + " " + 'i' + " " +'j' + "\n") else system.out.println(); row++; } system.out.println(); } for(int row=0; row<seats.length-1; row++){ for(int column=0; column<seats[row].length-1; column++){ system.out.print(seats[row+1][column]);] } system.out.println(); } }//main }//class
the main issue you're using length-1
.
it should this:
for(int row=0; row < seats.length; row++){ for(int column=0; column <s eats[row].length; column++){
...or this:
for(int row=0; row <= seats.length-1; row++){ for(int column=0; column <= seats[row].length-1; column++){
plus never intialized seats[][]
value. that's why null
being printed.
i fixed compile errors (there lot), , here code @ least runs, , populates seats
matrix;
also, if want print out "row 1" through "row 20", add 1 when specifying row number, since arrays 0 based. array of size 20 indexed 0 through 19;
edit: after comment, think close want:
public class cinema_seats { public static void main(string[] args){ string[][] seats = new string[20][10]; string seat = "abcdefghijklmnopqrstuvwxyz"; for(int row=0; row<seats.length; row++){ for(int column=0; column<seats[row].length; column++){ seats[row][column] = new string (character.tostring(seat.charat(column))); } } for(int row=0; row<seats.length; row++){ system.out.print("row: " + (row + 1) + " "); for(int column=0; column<seats[row].length; column++){ system.out.print(seats[row][column] + " "); } system.out.println(); } } }//main
output:
row: 1 b c d e f g h j row: 2 b c d e f g h j row: 3 b c d e f g h j row: 4 b c d e f g h j row: 5 b c d e f g h j row: 6 b c d e f g h j row: 7 b c d e f g h j row: 8 b c d e f g h j row: 9 b c d e f g h j row: 10 b c d e f g h j row: 11 b c d e f g h j row: 12 b c d e f g h j row: 13 b c d e f g h j row: 14 b c d e f g h j row: 15 b c d e f g h j row: 16 b c d e f g h j row: 17 b c d e f g h j row: 18 b c d e f g h j row: 19 b c d e f g h j row: 20 b c d e f g h j