Convert Array into a primative method to express the same result, using no LINQ only int.

前端 未结 4 378
萌比男神i
萌比男神i 2021-01-27 10:39

my program records the number of bottles four rooms has collected in a bottle drive. When the user types in quit, the number of bottle each room has collected is shown as well a

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-27 11:17

    You can not replace an array easily with individual variables. If you have a declaration like

    int room1 = 0, room2 = 0, room3 = 0, room4 = 0;
    

    and want to access room number i then you have to write

    switch (i) {
        case 1:
            Console.WriteLine(room1);
            break;
        case 2:
            Console.WriteLine(room2);
            break;
        case 3:
            Console.WriteLine(room3);
            break;
        case 4:
            Console.WriteLine(room4);
            break;
    }
    

    With an array you can simply write

    Console.WriteLine(rooms[i]);
    

    If you really want to go this array-less way, I suggest you to use helper methods:

    private void SetRoom(int room, int value)
    {
        switch (room) {
            case 1:
                room1 = value;
                break;
            case 2:
                room2 = value;
                break;
            case 3:
                room3 = value;
                break;
            case 4:
                room4 = value;
                break;
        }
    }
    
    public int GetRoom(int room)
    {
        switch (room) {
            case 1:
                return room1;
            case 2:
                return room2;
            case 3:
                return room3;
            case 4:
                return room4;
            default:
                return 0;
        }
    }
    

    You must declare variables room1 to room4 as class members to make this work.

    Now you can write:

    Console.WriteLine(GetRoom(i));
    

    Or instead of rooms[i] += n;

    SetRoom(i, GetRoom(i) + n);
    

提交回复
热议问题