我必须制作一个价格(值)位于多维数组上的方法,它只需要返回一组坐标。问题是其他位置具有相同的值,因此它返回位置处的所有坐标,而不仅仅是第一个坐标。
public static int availSeats(int a[][], int seatPrice){
int seats=seatPrice;
for(int row=0;row<rows;row++){
for(int col=0;col<cols;col++){
if(seats==a[row][col]){
int priceRow=row;
int priceCol=col;
System.out.println("Seat: "+priceRow+","+priceCol);
}
}}
return seats;
}
答案 0 :(得分:0)
您的代码必须只返回一个值,但它会全部打印。我假设返回值是正确的,这是你实际期望的。因此,避免混淆,在外环上添加标签,并在遇到第一个满足坐标时将其打破。例如,更改您的代码如下:
int seats=seatPrice;
outerloop:
for(int row=0;row<rows;row++){
for(int col=0;col<cols;col++){
if(seats==a[row][col]){
int priceRow=row;
int priceCol=col;
System.out.println("Seat: "+priceRow+","+priceCol);
break outerloop;
}
}}
return seats;
答案 1 :(得分:0)
我不确定目标,但我想List可以提供帮助:
public static List<Coordinate> availSeats(int a[][], int seatPrice){
List<Coordinate> coords= new ArrayList<Coordinate>();
int seats=seatPrice;
for(int row=0;row<rows;row++){
for(int col=0;col<cols;col++){
if(seats==a[row][col]){
int priceRow=row;
int priceCol=col;
coords.add(new Coordinate(row, col));
System.out.println("Seat: "+priceRow+","+priceCol);
}
}}
return coords;
}
其中坐标是一个包含两个int字段的简单类:row和col。