1 回答
TA贡献1812条经验 获得超5个赞
这是一个更好地理解的示例,我在这里涵盖了一个案例,因为其余的都相当相同
//private variable here so we could find and book seat through method findAvailableSeat()
private static int[][] table = { { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }, { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 },
{ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }, { 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 },
{ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 }, { 30, 30, 30, 30, 30, 30, 30, 30, 30, 30 },
{ 40, 40, 40, 40, 40, 40, 40, 40, 40, 40 }, { 40, 40, 40, 40, 40, 40, 40, 40, 40, 40 },
{ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 }, };
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean done = false;
// initial seating chart
while (!done) {
int row;
int col;
// search seating chart
System.out.printf("Enter maximum amount that you would like to spend on the tickets: ");
int amount = in.nextInt();
if (10 <= amount && amount < 20) {
String location = findAvailableSeat(10);//store the indexes in a variable to show the user later
if(location != null) {
String[] locationList = location.split(",");
row = Integer.parseInt(locationList[0]);
col = Integer.parseInt(locationList[1]);
System.out.printf("Ticket located at Row %d Seat %d purchased for 10\n", row + 1, col + 1);
System.out.print("Would you like to purchase additional tickets? (Y/N) ");
String resp = in.next(); //this statement is needed as sometimes with in.next() rushes to user input without printing text
if (resp.equals("Y")) {
done = false;
} else {
done = true;
}
}
else
System.out.printf("No available seat found\n");
}
}
}
在方法中,我们有
private static String findAvailableSeat(int i) {
// TODO Auto-generated method stub
for (int row=0; row<9; row++) {
for (int col=0; col<8; col++) {
if(table[row][col]==i) {
//find the seat location, set location to 0 and then return indices to show in user result
table[row][col] = 0;
return row + "," + col;
}
}
}
return null;
}
添加回答
举报