【问题标题】:Can someone turn this array code into a non-array method to acheive the same results?有人可以将此数组代码转换为非数组方法以达到相同的结果吗?
【发布时间】:2012-01-14 20:22:01
【问题描述】:

我这里有一段代码,记录了 4 个房间收集的瓶子数量。当用户输入退出时,程序会吐出每个房间收集的瓶子数量,并确定收集瓶子数量最多的房间。我使用了数组方法,但我不应该使用这种方法,只是为了展示数组的有用性。任何人都可以给我任何指示吗?

namespace BottleDrive
  {
      class Program
    {
        static void Main(string[] args)
        {//Initialize array of 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 allows quit to jump out of loop
                    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. An alternative to below
            /*for (int i = 0; i < rooms.Length; ++i)
                Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);*/

            int maxValue = 0;//initiates the winner, contructor starts at 0
            int maxRoomNumber = 0;//initiates the room number that wins
            for (int i = 0; i < rooms.Length; ++i)//This loop goes through the array of rooms (4)
            {
                if (rooms[i] > maxValue)//Makes sure that the maxValue is picked in the array
                {//Looking for room number for the 
                    maxValue = rooms[i];
                    maxRoomNumber = i + 1;
                }//Writes the bottles collected by the different rooms
                Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);
            }
            //Outputs winner
            Console.WriteLine("And the Winner is room " + maxRoomNumber + "!!!");

        }
          }
            }

【问题讨论】:

  • 您可以使用List&lt;int&gt; 和 LINQ 来展示无用的数组是如何...
  • LINQ 是我的班级尚未涉及的内容。还有比 LINQ 更原始的方式吗?
  • 插入强制性指针笑话...“这里有一些... 0x013d2da0 和 0x4e326dbb”
  • @Marc - 是时候升级到 64 位了,你不觉得吗? ;-)

标签: c# arrays methods


【解决方案1】:

如果不允许使用数组,则可以为所有数组项声明 4 个变量。

int room1, room2, room3, room4;

我想这就是本练习的预期方法。

【讨论】:

  • 如果我 int room1、room2、room3、room4,我如何使用数组调用线使其适合我的 intiated 房间号? Console.Write("房间 {0} 收集的瓶子:", room); // 此行添加瓶子的数量并记录它,以便您可以连续统计收集的瓶子。房间[房间 - 1] += int.Parse(Console.ReadLine());因为我是通过数组调用的,所以我如何调用单个启动的房间?
  • 这将是room1 = int.Parse( ... ); room2 = int.Parse( ... )等;
【解决方案2】:

这是一个使用类来保存每个房间信息的示例。使用类的原因是,如果您的程序将来需要更改以收集更多信息,您不必再跟踪另一个数组,只需向类添加属性即可。

各个房间现在保存在一个列表中,而不是一个数组中,只是为了显示不同的结构。

这是新的 Room 类:

public class Room
{
    public int Number { get; set; }
    public int BottleCount { get; set; }

    public Room(int wNumber)
    {
        Number = wNumber;
    }
}

这是该程序的新版本。请注意,已添加对最终用户输入的值的额外检查,以防止在尝试获取当前房间或将用户输入的值解析为 int 时出现异常:

    static void Main(string[] args)
    {
        const int MAX_ROOMS = 4;
        var cRooms = new System.Collections.Generic.List<Room>();

        for (int nI = 0; nI < MAX_ROOMS; nI++)
        {
            // The room number is 1 to 4
            cRooms.Add(new Room(nI + 1));
        }

        // Initializes the room that wins
        //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 roomNumber = Console.ReadLine();
            if (roomNumber == "quit")
            {
                //Break statement allows quit to jump out of loop
                break;
            }
            int room = 0;
            if (int.TryParse(roomNumber, out room) && (room < MAX_ROOMS) && (room >= 0)) {
                Room currentRoom;

                currentRoom = cRooms[room];

                Console.Write("Bottles collected in room {0}: ", currentRoom.Number);

                int wBottleCount = 0;

                if (int.TryParse(Console.ReadLine(), out wBottleCount) && (wBottleCount >= 0))
                {
                    // This line adds the count of bottles and records it so you can continuously count the bottles collected.
                    currentRoom.BottleCount += wBottleCount;
                }
                else
                {
                    Console.WriteLine("Invalid bottle count; value must be greater than 0");
                }
            }
            else
            {
                Console.WriteLine("Invalid room number; value must be between 1 and " + MAX_ROOMS.ToString());
            }
        }

        Room maxRoom = null;

        foreach (Room currentRoom in cRooms) //This loop goes through the array of rooms (4)
        {
            // This assumes that the bottle count can never be decreased in a room
            if ((maxRoom == null) || (maxRoom.BottleCount < currentRoom.BottleCount))
            {
                maxRoom = currentRoom;
            }
            Console.WriteLine("Bottles collected in room {0} = {1}", currentRoom.Number, currentRoom.BottleCount);
        }
        //Outputs winner
        Console.WriteLine("And the Winner is room " + maxRoom.Number + "!!!");
    }

【讨论】:

    猜你喜欢
    • 2011-05-31
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2016-03-11
    相关资源
    最近更新 更多