我正在尝试为拍卖创建代码,以便拍卖开始时给狗一个编号。创建的第一个拍卖将获得编号1,其次是编号2,依此类推。
问题是,拍卖代码没有按拍卖列出狗。而是按注册列出。
例如: 犬只
(拍卖过程)
命令:开始拍卖
狗名:Maya
输出:Maya已放入拍卖#2
命令:开始拍卖
狗名:Bowie
输出: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);
我是一个初学者,有点困惑。有任何解决方法的想法吗?
答案 0 :(得分:0)
这里的问题是,在获得要拍卖的狗的名字之后,您在列表中搜索该狗,并打印出该狗在列表中的位置的索引。解决此问题所需要做的是有另一个计数器变量,该变量对拍卖狗的数量进行计数,每次递增。代码看起来像这样:
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);
}