Bus Seat Reservation code amendment in Java

时间:2016-12-26 16:31:15

标签: java multidimensional-array

I was trying this bus seat reservation code, and found this code somewhere here. I was wondering if you could help me change the result. Instead of 0 the seat entered will be "R".

I'm not familiar to Java.

import java.io.*;
public class busseatreservation {

public static void printRow(int[] row) {
     for (int i : row) {
        System.out.print(i);
        System.out.print("\t");
    }
    System.out.println();
}

 public static void main(String[] args)throws Exception {
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));   
 int twoDm[][]= new int[5][7];
    int i,j,k=1;
    double ans;

    for(i=0;i<5;i++) {
        for(j=0;j<7;j++) {
            twoDm[i][j]=k;
            k++;
        }
    }

    for(int[] row : twoDm) {
        printRow(row);
    }

    for (int l = 0; l < 5; l++) {
        System.out.print("Enter a Seat number to reserve: ");
        ans = Integer.parseInt(br.readLine());
        k = 1;
        for(i=0;i<5;i++) {
            for(j=0;j<7;j++) {
                if (k == ans) {
                    if (twoDm[i][j]== 0) {
                        System.out.println("That seat has already been reserved");
                    }
                    else {
                         twoDm[i][j]= 0;
                    }
                }
                k++;
            }
        }
        for(int[] row : twoDm) {
            printRow(row);
        }
   }

}
}

1 个答案:

答案 0 :(得分:0)

首先,您将元素保存在整数数组中。所以不可能有这个数组的元素'R'。要编写'R',您应该将元素保存在字符串数组中。您应该使用数字作为字符串。使用此方法,字母和数字都可以是数组的元素。

另一种不好的解决方案,如果相应的元素为0,则可以打印R。

另一点是;如果用户输入预留座位,您的程序只会发出5次警告。你应该看看它。

晚上好。

相关问题