我试图为拍卖创造一个代码,以便当拍卖开始时,狗会得到一个数字。第一次拍卖将获得第一名,第二名,以此类推。
问题是,拍卖的代码没有按拍卖列出狗的名单。相反,它是按登记列出的。
例如:注册狗
(拍卖过程)
命令:开始拍卖
狗名:玛雅
输出:玛雅已被拍卖#2
命令:开始拍卖
狗名:鲍伊
输出: Bowie已被拍卖#0
这是我的密码:
private void startAuction() {
boolean current = false;
do {
System.out.println("Dog name: ");
String dogName = scan.nextLine().toLowerCase().trim();
if (dogName.isEmpty()) {
System.out.println("Error: Name can't be empty.");
continue;
}
for (int i = 0; i < dogs.size(); i++) {
if (dogName.equals(dogs.get(i).getName())) {
auction.add(new Auction(dogName));
System.out.printf(dogName + " has been put up for auction in auction #%d", i);
System.out.println();
current = true;
return;
}
}
if (current == false) {
System.out.println("Error: no such dog in the register");
}
} while(true);我是个初学者,有点困惑。有什么办法解决这个问题吗?
发布于 2019-02-13 12:15:59
这里的问题是,在将狗的名字拍卖后,你在列表中搜索那只狗,打印狗在列表中的位置的索引。要解决这个问题,您需要做的是使用另一个计数器变量来计数被拍卖的狗的数量,每次递增。代码应该如下所示:
private void startAuction() {
boolean current = false;
int auctionCount = 1;//Declare the current auction we are on
do {
System.out.println("Dog name: ");
String dogName = scan.nextLine().toLowerCase().trim();
if (dogName.isEmpty()) {
System.out.println("Error: Name can't be empty.");
continue;
}
for (int i = 0; i < dogs.size(); i++) {
if (dogName.equals(dogs.get(i).getName())) {
auction.add(new Auction(dogName));
//Use the auction count here so that it starts at 1 and increases
System.out.printf(dogName + " has been put up for auction in auction #%d", auctionCount);from there
System.out.println();
auctionCount++;//Make sure the next auction has a number that is one larger
current = true;
return;
}
}
if (current == false) {
System.out.println("Error: no such dog in the register");
}
} while(true);
}https://stackoverflow.com/questions/54669797
复制相似问题