我正在制作一个瓶子收集程序。我正在输入4个房间的瓶子收集,当用户输入退出时,会显示房间收集的瓶子清单,并选择获胜者。我的代码现在选择了最高记录瓶数,但我希望它显示具有该瓶数的房间号。如何更改我的代码以使其正常工作?
namespace BottleDrive
{
class Program
{
static void Main(string[] args)
{ //Initialize loop rooms to 4
int[] rooms = new int[4];
//Start of while loop to ask what room your adding into.
while (true)
{
Console.Write("Enter the room you're in: ");
//If user enters quit at anytime, the code will jump out of while statement and enter for loop below
string quit = Console.ReadLine();
if (quit == "quit")
//Break statement separates embedded statement and is needed inorder to allow
break;
//Variable room holds the number of bottles collect by each room.
int room = int.Parse(quit);
Console.Write("Bottles collected in room {0}: ", room);
// This line adds the count of bottles and records it so you can continuously count the bottles collected.
rooms[room - 1] += int.Parse(Console.ReadLine());
}
//This for statement lists the 4 rooms and their bottle count when the user has entered quit.
for (int i = 0; i < rooms.Length; ++i)
Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);
Console.WriteLine("And the Winner is room " + rooms.Max().ToString() + "!!!");
}
}
}
答案 0 :(得分:2)
试试这个:
int maxValue = 0;
int maxRoomNumber = 0;
for (int i = 0; i < rooms.Length; ++i)
{
if (rooms[i] > maxValue)
{
maxValue = rooms[i];
maxRoomNumber = i + 1;
}
Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);
}
Console.WriteLine("And the Winner is room " + maxRoomNumber + "!!!");
答案 1 :(得分:1)
你对rooms.Max()
的使用很接近,只是它会返回最大值并且你想要索引。
您可以使用简单的for
循环来查找索引。否则,你could go with an elegant "LINQ" method。
注意:不要忘记允许多个房间具有相同最大值的情况!
答案 2 :(得分:1)
我想知道为什么LINQ没有包含IndexOf()扩展名。我最终编写了自己的项目:
public static class Extensions
{
public static int IndexOf<T>(this IEnumerable<T> items, Predicate<T> predicate)
{
int index = 0;
foreach (T item in items)
{
if (predicate(item))
break;
index++;
}
return index;
}
public static int IndexOf<T>(this IEnumerable<T> items, T value)
{
int index = 0;
foreach (T item in items)
{
if (item.Equals(value))
break;
index++;
}
return index;
}
}
你可以这样做:
Console.WriteLine("And the Winner is room " + rooms.IndexOf(rooms.Max()));