I have a hw assignment that says to create a win form app that lets the user click on any day of the month of January 2018. Then display four pieces of data about the weather of that day.
steps:
First read the weather.txt file which holds each days weather data(eg 1/13/2018;0;36;13) and split the 4 pieces of data into four fields of a struct and create an instance of that day. Then store that day in a list.
My problem:
How do I create an instance of a struct dynamically like that. The only thing coming to my mind is looping through each day of the month changing the var name incrementally like [structObj] d[i] = new [structObj](string date, int precipitation, int temp);
where [i] changes the name with the loop and then I've easily populated a months worths of structs into my list. This doesn't work:(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Weather_data
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
struct WeatherData
{
private string date { get; set; }
private int precipitation { get; set; }
private int hiTemp { get; set; }
private int lowTemp { get; set; }
public WeatherData(string date, int precipitation, int hiTemp, int lowTemp)
{
this.date = date;
this.precipitation = precipitation;
this.hiTemp = hiTemp;
this.lowTemp = lowTemp;
}
}
private void button1_Click(object sender, EventArgs e)
{
//change FILE PATH for weather.txt here--->
string[] lines = File.ReadAllLines(@"C:\Users\sethr\Desktop\C#\M9SPabst\Weather data\Weather data\weather.txt");
for(int i = 0; i < lines.Length; i++)
{
string[] data = lines[i].Split(';');
WeatherData d = new WeatherData(data[0],
Convert.ToInt32(data[1]),
Convert.ToInt32(data[2]),
Convert.ToInt32(data[3]));
}
}
}
}
Assuming the FileReadsAllLines reads corretly you would add the list to your code. And then add each element. You will need a component to display the list in the UI.
List<WeatherData> wheatherDataList = new List<WeatherData>();
private void button1_Click(object sender, EventArgs e)
{
//change FILE PATH for weather.txt here--->
string[] lines = File.ReadAllLines(@"C:\Users\sethr\Desktop\C#\M9SPabst\Weather data\Weather data\weather.txt");
for (int i = 0; i < lines.Length; i++)
{
string[] data = lines[i].Split(';');
WeatherData d = new WeatherData(data[0],
Convert.ToInt32(data[1]),
Convert.ToInt32(data[2]),
Convert.ToInt32(data[3]));
wheatherDataList.Add(d);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.