Home > other >  how to input 2 digits in a char in my case
how to input 2 digits in a char in my case

Time:01-01

I have this code that is based on seats but the rows exceeded to 10 . When i input 1A it will change the seat row 1 column a from '*' to 'x'. Now my problem is when it comes to 2 digits e.g. 12B, it will give me error because it only takes the '1' not the whole '12' in a char that detects the row to change it to 'x'.

I kind of have the idea on my problem, it is because it's character and follows ASCII but can't seem to find the solution to my problem. I know this is a assignment and got some of the code references from this site also, but i study them as i took some references, not just copy and paste.

This is where i get stuck

if (choice == 'c') {
            input.nextLine();
            String seatchoice = input.nextLine();
            char[][] seats = new char [13][6]; 
            for(i = 0; i < 13; i  ) {
                seats[i][0] = '*';
                seats[i][1] = '*';
                seats[i][2] = '*';
                seats[i][3] = '*';
                seats[i][4] = '*';
                seats[i][5] = '*'; 
            }
            while (seatchoice.length() > 0 ) {
                int row = seatchoice.charAt(0) - '1';
                int col = seatchoice.charAt(1) - 'A';
                if (seats[row][col] != 'x') {
                    seats[row][col] = 'x';
                    System.out.println(" ");
                    printSeats(seats);
                }
        }
       }

the method printSeats

private static void printSeats(char[][] seats) {
         System.out.println("\t A B C D E F");
         for (int i = 0; i < seats.length; i  ) {
             System.out.println("Row "   (1   i)   "\t "   seats[i][0]   " "   seats[i][1]   " "   seats[i][2]   " " 
           seats[i][3]   " "   seats[i][4]   " "   seats[i][5]);
         }
          
     }

Now, when i try inputting "10A" it will give me, Index -17 out of bounds for length 6. I'm expecting it to change the row 10 column A to be x A B C D E F Row 8 * * * * * * Row 9 * * * * * * Row 10 x * * * * * Row 11 * * * * * * Row 12 * * * * * * Row 13 * * * * * *

Thank you in advance. Please correct me in any ways or if there's something that i should learn. I'm willing to accept any criticism.

CodePudding user response:

Since the Letter is always in the last index you can do it this way

int row = Integer.parseInt(seatchoice.substring(0, seatchoice.length() - 1)) - 1;
int col = seatchoice.charAt(seatchoice.length() - 1) - 'A';
  • Related