我想知道我是否可以获得一些Java代码的快速帮助。我创建了一个阵列,每个位置/座位都有一个特定的“价格”。我需要编写一个程序,要求用户选择座位或价格。我已经完成了上半部分找到用户输入选择的特定座位位置并将其替换为0但是我在下半年遇到用户所需的座位价格并将其更改为0时遇到了问题。以他们选择的价格选择多个座位,所以我只需要随机选择一个并将其更改为0.我会删除一堆代码以便于阅读,但基本上我需要帮助的是底部:< / p>
Scanner in = new Scanner(System.in);
String seat = "";
String price = "";
int[][] seating = new int[][]
{
{ 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, 10, 10, 10 },
{ 10, 10, 20, 20, 20, 20, 20, 10, 10, 10 },
{ 10, 10, 20, 20, 20, 20, 20, 10, 10, 10 },
{ 10, 10, 20, 20, 30, 30, 20, 20, 10, 10 },
{ 20, 20, 30, 30, 40, 40, 30, 30, 20, 20 },
{ 20, 30, 30, 40, 50, 50, 40, 30, 30, 20 },
{ 30, 40, 50, 50, 50, 50, 50, 50, 40, 30 },
};
System.out.println("\nHere is a map of the current seating:\n");
printArray(seating);
System.out.println("\nWould you like to pick a seat or a price?\n");
String decision = in.nextLine();
if(decision.equals("price"))
{
System.out.println("\nWould you like to pay 10, 20, 30, 40, or 50 dollars?\n");
int pickedPrice = in.nextInt();
//HELP HERE //replace a random seat with the selected price to 0 in the array
}
我只是作为最后的手段来到这里,因为我看到了整个地方,找不到任何帮助。在此先感谢,我真的很感激!
答案 0 :(得分:1)
这里有几个选项。我想考虑的两个是下面的。
如果您选择第一个选项,它将看起来像这样。
do {
Random generator = new Random();
int row = generator.nextInt(seating.length);
int seat = generator.nextInt(seating.length);
} while(seating[row][seat] != pickedPrice);
seating[row][seat] = 0;
当然,如果只采取一个座位,这种方法效率低下。如果您选择解决第二个选项,它会更有效,但代码会更复杂。
ArrayList<Point> matches = new ArrayList<>();
for(int row = 0; row < seating.length; row++) {
for(int seat = 0; seat < seating[0].length; seat++) {
if(seat == pickedPrice)
matches.add(new Point(row, seat));
}
}
Random generator = new Random();
Point p = matches.get(generator.nextInt(matches.size()));
seating[p.x][p.y] = 0;