'Can someone help me with looping through this array? Beginner coder here... it wont successfully run [duplicate]
I can't seem to successfully run the program. I'm only a couple weeks into learning c# and I can't seem to find a solution to this problem..
What I have to do is implement a loop into this project and I was thinking about looping my DisplayInfo method to display all 4 houses as well as all the info about them at the same time.
public class Houses
{
public string Address;
public string Color;
public int Price;
public int RoomNumbers;
public void DisplayInfo()
{
Console.WriteLine($"Address: {Address}");
Console.WriteLine($"The color of the propery is: {Color}");
Console.WriteLine($"The price of this property is valued at ${Price}");
Console.WriteLine($"This property has {RoomNumbers} rooms.");
}
}
class Program
{
static void Main(string[] args)
{
Houses[] house = new Houses[4];
{
house[0].Address = "55 New Bridge Ln.";
house[0].Color = "Red";
house[0].Price = 200000;
house[0].RoomNumbers = 2;
house[1].Address = "101 Coders Dr.";
house[1].Color = "Yellow";
house[1].Price = 250000;
house[1].RoomNumbers = 3;
house[2].Address = "2041 Hungry Man Cir.";
house[2].Color = "Green";
house[2].Price = 350000;
house[2].RoomNumbers = 5;
house[3].Address = "3080 Falmoth Dr.";
house[3].Color = "Purple";
house[3].Price = 400000;
house[3].RoomNumbers = 6;
}
for (int i = 0; i < house.Length; i++)
{
house[i].DisplayInfo();
}
}
} }
Solution 1:[1]
you are missing object initialization for single house, you can do it like this:
var house = new Houses[]
{
new Houses{
Address = "55 New Bridge Ln.",
Color = "Red",
Price = 200000,
RoomNumbers = 2
},
new Houses{
Address = "33 New Bridge Ln.",
Color = "Orange",
Price = 300000,
RoomNumbers = 1
}
///...
};
for (int i = 0; i < house.Length; i++)
{
house[i].DisplayInfo();
}
in addition you can move to foreach loop
foreach(var singleHouse in house)
{
singleHouse.DisplayInfo();
}
in general I would use a constructor in your Houses class
public class Houses
{
public Houses(string address, string color, int price, int roomNumbers)
{
Address = address;
Color = color;
Price = price;
RoomNumbers = roomNumbers;
}
...
var house = new Houses[]
{
new Houses("55 New Bridge Ln.", "Red", 200000, 2),
new Houses("33 New Bridge Ln.", "Orange", 300000, 1)
///...
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
