I'm making a telegram bot with c#.
I want to read a number of names (not more than 20 tough thy could be less) and give them to the user as keyboardMarkup. With a one dimensional array they go all in one line and it's unreadable. I wanted to make 4 line with 5 names so i tried a 4x5 array. But i get this error
Error CS0029 Cannot implicitly convert type 'NetTelegramBotApi.Types.KeyboardButton[,]' to 'NetTelegramBotApi.Types.KeyboardButton[][]'
if (text == "/lista")
{
// Read a text file line by line.
listapz = System.IO.File.ReadAllLines("listapz.txt");
string selezione = "Seleziona il paziente:";
int i = 0;
int x = 0;
int y = 0;
var arrays = new KeyboardButton[4,5];
for (i = 0; i < listapz.Length; i++)
{
y = i / 5;
x = i - (y * 5);
arrays[y,x] = new KeyboardButton("$" + (i + 1) + " " + listapz[i]);
selezione += "\n$" + (i + 1) + " " + listapz[i] + "";
}
var keyb = new ReplyKeyboardMarkup()
{
Keyboard = arrays,
OneTimeKeyboard = true,
ResizeKeyboard = true
};
var reqAction = new SendMessage(update.Message.Chat.Id, selezione) { ReplyMarkup = keyb };
bot.MakeRequestAsync(reqAction).Wait();
Console.WriteLine(reqAction);
continue;
}
any solution?
You can create new one dimensional array for every line
Then
keyb.row(first_array) //you need get only values in python it will like keyb.row(*array)
keyb.row(second_array) //and so on
and add all keyboards in one reply_markup=keyb
Related
Is there any way I could use a loop instead of writing out all of these if/else statements? I'm not sure if it is possible and I have looked online and haven't seen very many guides that would help me.
int numberOne = random.Next(id2) + 1;
int numberTwo = random.Next(id2) + 1;
int numberThree = random.Next(id2) + 1;
int numberFour = random.Next(id2) + 1;
int numberFive = random.Next(id2) + 1;
if (id1 == 1)
{
int total = numberOne;
string newmessage = "message";
return Json(newmessage);
}
else if(id1 == 2)
{
int total = numberOne + numberTwo;
string newmessage = "message";
return Json(newmessage);
}
else if (id1 == 3)
{
int total = numberOne + numberTwo + numberThree;
string newmessage = "message";
return Json(newmessage);
}
else if (id1 == 4)
{
int total = numberOne + numberTwo + numberThree + numberFour;
string newmessage = "message";
return Json(newmessage);
}
else if (id1 == 5)
{
int total = numberOne + numberTwo + numberThree + numberFive;
string newmessage = "message";
return Json(newmessage);
}
What you likely want to do is:
int total = Enumerable.Range(1, id1).Sum(z => random.Next(id2) + 1);
string newmessage = "message";
return Json(newmessage);
There is no need for an explicit loop (since Enumerable.Range will do the looping for you).
Since you probably need a loop and not using lambdas, you can go with something like this:
int total = 0;
for (int i = 0; i < id1; i++)
{
total += random.Next(id2) + 1;
}
return Json("message"); // I assume you want to return total here;
The reason this works is that if id1 is 1, you'd break out of the loop after doing 1 random.Next. If id2 is 2, then you'd run thru the first number and then add the 2nd number automatically. With this approach, you could support any number, not just up to 5.
I'd go with #mjwills solution, but here's an explanation of how you might do it in a step by step fashion:
The first thing I did was declare random, id1 and id2. I varied id1 during testing. When you post code, you should include this kind of thing, that way the folks help you don't have to reverse engineer what you are thinking:
var id1 = 5;
var id2 = 10;
var random = new Random();
Then, I realize that in each case, you have a chunk of the same code (the last two lines), so I extracted that duplicated code out and put it at the bottom of the loop (and I used NewtonSoft's JsonConvert class to convert things to JSON (which I'm assuming your Json function does) - I have that NuGetted into my test project):
string newMessage = "message";
return JsonConvert.SerializeObject(newMessage);
Finally, here's the loop you were asking about. I initialize total (I could put that initialization in the for loop, but it's clearer this way). Also note that the for loop is non-standard, it loops from 1 to N inclusive (generally for loops are 0 to N-1). This loop is between the initialization code and the final code:
var total = 0;
for (var i = 1; i <= id1; ++i)
{
total += (random.Next(id2) + 1);
}
What #mjwills code does is convert that into a single expression. The Enumerable.Range(1, id1) part generates a collection of consecutive integers starting at 1 and having id1 entries. Then he calls .Sum, passing it a lambda that represents a function to run on each item in the collection before it is summed. My loop basically does the same thing.
Altogether, it looks like this:
var id1 = 5;
var id2 = 10;
var random = new Random();
var total = 0;
for (var i = 1; i <= id1; ++i)
{
total += (random.Next(id2) + 1);
}
string newMessage = "message";
return JsonConvert.SerializeObject(newMessage);
try this, it also allows you init 5 numbers using any algoritm, not just the same
//var random=new Random();
//var id2=2;
//var id1=4;
var data = new int[]{
random.Next(id2) + 1,
random.Next(id2) + 1,
random.Next(id2) + 1,
random.Next(id2) + 1,
random.Next(id2) + 1
};
var total=0;
for ( var i = 0; i < id1; i++)
{
total+=data[i];
}
var newmessage = $"message#{id1.ToString()}, total {total.ToString()} ";
return Json(newmessage);
so in unity im creating randomly generating rooms. inside of these rooms i will "randomly" place objects, enemy,objects,items etc. based on nodes. nodes are transform objects that are separated from each other by 1 unit. the idea is that i can now pick a node and instantiate something at that node. The code works great when the room is 10x10(x,z since its a 3d game) i get a nice grid pattern it also works as expected when x is any multiple of 2. however when z changes from 10 it doesn't create the grid properly. there is also a problem if the room changes locations other then 0,0.
floor is a child object of the room.
void RoomSetup()
{
bool first = true;
int collCount = -1;
GameObject placeHolder = new GameObject("temp");
float colls;
float offX, offZ;
colls = floor.transform.localScale.x - 1;
print(colls);
for (int i = 0; i < ((floor.transform.localScale.x-1)
*(floor.transform.localScale.z-1)); i++)
{
//creating a for loop that stops when its greater then the area of the rectangle, subtract one from x,z so theres a one unit of padding from the walls.
offX = floor.transform.lossyPosition.x;
offZ = floor.transform.lossyPosition.z;
//getting the offset of the room in world space this is where i believe the issues arise
collCount++;
GameObject temp = new GameObject(i + " Node");
temp.transform.SetParent(floor.transform);
temp.AddComponent<BoxCollider>();
temp.GetComponent<BoxCollider>().isTrigger = true;
if(!first)
{
temp.transform.position = new Vector3((placeHolder.transform.position.x + 1), 6, placeHolder.transform.position.z);
placeHolder = temp;
if (collCount >= colls)
{
print("new line on " + temp.name + " coll " + collCount);
collCount = 0;
placeHolder.transform.position = new Vector3((-(floor.transform.localScale.x / 2) + 1)+offX, 6, (placeHolder.transform.position.z - 1)-offZ);
}
}
if (first)
{
// print(colls);
temp.transform.position = new Vector3((-(floor.transform.localScale.x / 2) + 1) + offX, 6, floor.transform.localScale.z - offZ);
placeHolder = temp;
first = false;
}
nodes.Add(temp);
}
}
Here are some pictures to help illustrate the issue
the first image is when the room is at 0,0 and it creates a nice grid pattern
when the room is offest it creates the grid still at 0,0
i figured it out, it happend to do with with the local and world scale/pos of the floor and the room
void RoomSetup()
{
bool first = true;
int collCount = -1;
GameObject placeHolder = new GameObject("temp");
float colls;
colls = floor.transform.localScale.x - 1;
offX = floor.transform.localScale.x;
offZ = floor.transform.localScale.z;
offX = (offX / 2) - offX + 1;
offZ = (offZ / 2) - 1;
offX = offX + floor.transform.position.x;
offZ = (offZ + floor.transform.position.z);
print(colls);
for (int i = 0; i < ((floor.transform.localScale.x-1) * (floor.transform.localScale.z-1)); i++)
{
collCount++;
//print(collCount);
GameObject temp = new GameObject(i + " Node");
temp.transform.SetParent(floor.transform);
temp.AddComponent<BoxCollider>();
temp.GetComponent<BoxCollider>().isTrigger = true;
if(!first)
{
temp.transform.position = new Vector3((placeHolder.transform.position.x + 1), 6, placeHolder.transform.position.z);
placeHolder = temp;
if (collCount >= colls)
{
print("new line on " + temp.name + " coll " + collCount);
collCount = 0;
temp.transform.position = new Vector3(floor.transform.localPosition.x + offX, 6, placeHolder.transform.position.z - 1);
placeHolder = temp;
}
}
if (first)
{
// print(colls);
temp.transform.position = new Vector3(floor.transform.localPosition.x+offX, 6, floor.transform.localPosition.z+offZ);
placeHolder = temp;
first = false;
}
nodes.Add(temp);
}
}
works as intended, creates a grid of nodes on the floor of anyroom square room
I have searched through many posts and cannot find what I need. I see solutions to find the closest number to a target but I need one that finds that number, then can select the closest number on the other side of a "parabola" shaped set of data that is not completely symmetrical. I essentially use:
List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
int closest = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-
number) ? x : y);
This is how I find my first target number. Now I need to find a second number that is almost equal in value but on the other side of a parabola (I really need the indexes of these numbers but I can put the pieces together). My methods keeps coming up a single number. Essentially I need to move to an approximately symmetric index across a parabola to select an equivalent number. To put this in context, I am calculating beam width, i.e. the distance between the sides of a parabola at a specific point. Please let me know if this makes sense and if I need to explain more before you down vote me. I have done extensive research and testing. It is difficult for me to provide more code because it is coming from a $500,000 testing system that does not have internet so I can't copy and paste my code. I can go the extra yard if more code is needed though, just trying to avoid compromising an expensive embedded Windows system.
Here is a related post that I need to go a step further from
located here
Edit adding full code:
fileName = textBox10.Text;
SetupControlState(true);
if (comboBox2.SelectedIndex == 0)
{
cent = false;
}
else if (comboBox2.SelectedIndex == 1)
{
cent = true;
}
testHPositions = new List<double>();
testHMeasurements = new List<double>();
testVPositions = new List<double>();
testVMeasurements = new List<double>();
double horzRange = Double.Parse(textBox12.Text);
double vertRange = Double.Parse(textBox11.Text);
double refGain = Double.Parse(textBox14.Text);
double stepSize = Double.Parse(textBox13.Text);
testBorePos = new double[1, 2];
_worker = new BackgroundWorker();
_worker.WorkerSupportsCancellation = true;
testBoreRun.Enabled = false;
button2.Enabled = true;
_worker.RunWorkerAsync();
_worker.DoWork += new DoWorkEventHandler((state, args) =>
{
// try
// {
dev1 = new VisaDevice("inst0", "TCPIP0::192.168.0.10::inst0::INSTR"); //textBox1.Text);
if (!cent)
{
Double startfreq = double.Parse(textBox2.Text) * 1000000000;
Double stopfreq = double.Parse(textBox1.Text) * 1000000000;
dev1.SendBlocking("FREQ:STAR " + startfreq.ToString(), true);
string responseFreq = "";
dev1.QueryBlocking("FREQ:STAR?", ref responseFreq, true);
dev1.SendBlocking("FREQ:STOP " + stopfreq.ToString(), true);
dev1.QueryBlocking("FREQ:STOP?", ref responseFreq, true);
}
else if (cent)
{
Double freq = double.Parse(textBox9.Text) * 1000000000;
Double span = double.Parse(textBox8.Text) * 1000000000;
dev1.SendBlocking("FREQ:CENT " + freq.ToString(), true);
string responseFreq = "";
dev1.QueryBlocking("FREQ:CENT?", ref responseFreq, true);
dev1.SendBlocking("FREQ:SPAN " + span.ToString(), true);
dev1.QueryBlocking("FREQ:SPAN?", ref responseFreq, true);
// this.InvokeEx(f => f.stringReadTextBox.AppendText("Spectrum Analyzer Connected" + Environment.NewLine));
}
string progID;
Util U = new Util();
progID = "ASCOM.iOptron.Telescope";
if (progID != "")
{
PauseClass pause;
pause = new PauseClass();
Telescope T = new Telescope(progID);
T.Connected = true;
pause.Pause(5000);
T.Tracking = false;
T.TargetDeclination = 1;
T.TargetRightAscension = 1;
this.InvokeEx(f => f.stringReadTextBox.AppendText(" Connected to " + progID + Environment.NewLine));
this.InvokeEx(f => f.stringReadTextBox.AppendText(" Connected to Spectrum Analyzer" + Environment.NewLine));
T.SlewToAltAz(180.00, 45 - vertRange);
double Alt = T.Altitude;
for (int i = 0; i < ((vertRange * 2) / stepSize) + 1; i++)
{
if (_worker.CancellationPending)
break;
T.SlewToAltAz(180, Alt + stepSize * i);
this.InvokeEx(f => f.stringReadTextBox.AppendText("Test Altitude = " +(T.Altitude - 45).ToString("F") + Environment.NewLine));
testVPositions.Add(T.Altitude);
dev1.SendBlocking("INIT", true); //Start single measurement
string respOPC = "", responseState = "", responseMarkerY = "";
dev1.QueryBlocking("*OPC?", ref respOPC, true); //Wait for operation complete
dev1.QueryBlocking("STAT:QUES:MEAS?", ref responseState, true); //Check State
dev1.QueryBlocking("CALC:MARK:Y?", ref responseMarkerY, true); // Get the result
this.InvokeEx(f => f.stringReadTextBox.AppendText(responseMarkerY + Environment.NewLine));
testVMeasurements.Add(Double.Parse(responseMarkerY));
if (testVMeasurements.Count > ((vertRange * 2) / stepSize))
{
this.InvokeEx(f => f.stringReadTextBox.AppendText("Vertical Scanning Is Complete!" + Environment.NewLine));
double maxVamp = testVMeasurements.Max();
int index2 = testVMeasurements.IndexOf(testVMeasurements.Max());
double maxVPos = testVPositions[index2];
testBorePos[0, 1] = maxVPos;
this.InvokeEx(f => f.stringReadTextBox.AppendText("Vertical Max Amplitude = " + maxVamp + Environment.NewLine));
this.InvokeEx(f => f.stringReadTextBox.AppendText("Vertical Position of Max Amplitude = " + (maxVPos - 45).ToString("F") + Environment.NewLine));
}
}
if (!_worker.CancellationPending)
{
T.SlewToAltAz(180.00 - horzRange, testBorePos[0, 1]);
}
double Az = T.Azimuth;
for (int i = 0; i < ((horzRange * 2) / stepSize) + 1; i++)
{
if (_worker.CancellationPending)
break;
if (vertRange > 20)
{
this.InvokeEx(f => f.stringReadTextBox.AppendText("Vertical Range Cannot Be Greater than +/- 20 Degreez" + Environment.NewLine));
break;
}
T.SlewToAltAz(Az + stepSize * i,testBorePos[0,1]);
this.InvokeEx(f => f.stringReadTextBox.AppendText("Test Azimuth = " + (T.Azimuth-180).ToString("F") + Environment.NewLine));
testHPositions.Add(T.Azimuth);
dev1.SendBlocking("INIT", true); //Start single measurement
string respOPC = "", responseState = "", responseMarkerY = "", responseMarkerX = "";
// string responseFreq = "";
dev1.QueryBlocking("*OPC?", ref respOPC, true); //Wait for operation complete
dev1.QueryBlocking("STAT:QUES:MEAS?", ref responseState, true); //Check State
dev1.QueryBlocking("CALC:MARK:Y?", ref responseMarkerY, true); // Get the result
dev1.QueryBlocking("CALC:MARK:X?", ref responseMarkerX, true); // Get the result
this.InvokeEx(f => f.stringReadTextBox.AppendText(responseMarkerY + Environment.NewLine));
testHMeasurements.Add(Double.Parse(responseMarkerY));
if (testHMeasurements.Count > ((horzRange * 2) / stepSize))
{
_worker.CancelAsync();
stop = false;
this.InvokeEx(f => f.testBoreRun.Enabled = true);
this.InvokeEx(f => f.button2.Enabled = false);
this.InvokeEx(f => f.stringReadTextBox.AppendText("Horizontal Scanning Is Complete!" + Environment.NewLine));
double maxHamp =testHMeasurements.Max();
int index =testHMeasurements.IndexOf(testHMeasurements.Max());
double maxHPos =testHPositions[index];
testBorePos[0, 0] = maxHPos;
this.InvokeEx(f => f.stringReadTextBox.AppendText("Horizontal Max Amplitude = " + maxHamp + Environment.NewLine));
this.InvokeEx(f => f.stringReadTextBox.AppendText("Horizontal Position of Max Amplitude = " +( maxHPos-180).ToString("F") + Environment.NewLine));
this.InvokeEx(f => f.stringReadTextBox.AppendText("Antenna Under Test Peak Amplitude located at (" + (testBorePos[0, 0] - 180).ToString("F") + " , " + (testBorePos[0, 1] - 45).ToString("F") + ")" + Environment.NewLine));
this.InvokeEx(f => f.SetupControlState(false));
T.SlewToAltAz(testBorePos[0, 0], testBorePos[0, 1]);
dev1.SendBlocking("INIT", true); //Start single measurement
maxAmpTest = new double();
string respOPC2 = "", responseState2 = "", responseMarkerY2 = "";
dev1.QueryBlocking("*OPC?", ref respOPC2, true); //Wait for operation complete
dev1.QueryBlocking("STAT:QUES:MEAS?", ref responseState2, true); //Check State
dev1.QueryBlocking("CALC:MARK:Y?", ref responseMarkerY2, true); // Get the result
maxAmpTest = Double.Parse(responseMarkerY2);
double target = maxAmpTest - 3;
Here is where I am stuck:
// int indexbeam = testHMeasurements.IndexOf(target);
// indexList = testHMeasurements.IndexOf(testHMeasurements.FindAll(s => s.Equals(target)).First());
double closest = testHMeasurements.Aggregate((x, y) => Math.Abs(x - target) < Math.Abs(y - target) ? x : y);
var result = Enumerable.Range(0, testHMeasurements.Count).Where(j => testHMeasurements[j] ==closest).ToList();
// int beamIndex1 = testHMeasurements.IndexOf(testHMeasurements.OrderBy(item => Math.Abs(target - item)).First());
// int beamIndex2 = testHMeasurements.IndexOf(testHMeasurements.OrderBy(item => Math.Abs((beamIndex1 + 1) - item)).First());
double beam1 =( testHPositions[result[0]]) - 180;
double beam2 = (testHPositions[result[1]]) - 180;
beamWidth = Math.Abs(beam1) + Math.Abs(beam2);
this.InvokeEx(f => f.stringReadTextBox.AppendText("Antenna Under Test Amplitude = " + responseMarkerY2 + Environment.NewLine));
this.InvokeEx(f => f.stringReadTextBox.AppendText(" Antenna Under Test Gain = " + (maxAmpTest - refAmp + refGain) + Environment.NewLine));
this.InvokeEx(f => f.stringReadTextBox.AppendText(" Antenna Under Test Beam Width = " +beamWidth.ToString("F") + Environment.NewLine));
testGain = maxAmpTest - refAmp + refGain;
}
}
T.Connected = false;
T.Dispose();
dev1.Dispose();
if (_worker.CancellationPending)
{
Save();
// Cleanup Excel resources
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
});
First, you must find the parabola. Because your data only approximates the parabola, you need a statistical method called Quadratic Regression, or Polynomial Regression to find the parameters a, b and c of the equation
y = ax2 + bx + c
defining the parabola, that best fits the dataset given by the points
(xi, yi)
Use a math library or google for an algorithm.
Once you have the parabola, determine the symmetry axis of it, i.e. find the x-value of where the minimum or maximum (if the parabola is upside down) of the parabola is.
xs = -b / 2a
Now, once you have a given x-value, you can find a point at the opposite side of the parabola by mirroring x at xs
x' = 2xs - x
This is the explanation for a parabola in 2-D. If you have a parabola in 3-D, i.e. a Paraboloid the principle remains the same, but with more complex math. Google for Paraboloid Regression. A parabolic antenna has a curved surface with the cross-sectional shape of a parabola, called a paraboloid in geometrical terms.
Only once you have solved the mathematical problems, you can start programming and finding points in lists.
Turns out this question could actually be solved through programming with no advanced math required. Given a y-value and asked to find two corresponding x values on an asymmetrical/parabola arc you can simply split the arc at the vertex in two pieces then scan each of the two arrays for the matching x-value. It works like a charm - just requires a little critical thinking and a lot less over thinking it (math major stuff :p)
http://pastebin.com/98q57mzj
This has to do with a textbox array and an int array. Somehow, the values of the arrays seem to work within the main method, but not in other methods.
So from lines 34 to 44, I assign values to my arrays in the main, and then from lines 48 to 56 I use a for loop to make it so only certain keys are allowed when typing in the textboxes. Then in another method from lines 64 to 70, I try to use another for loop to make a "" string value equal to 0, or otherwise grab the value within the textbox and set that value to the variables within the numbers[] array. This doesn't seem to work. Changing the values in the textboxes doesn't seem to change the values of the numbers[] array. However, it does work if I type it out, as I did from lines 71 to 94. I don't want to take the easy way out and just type it out, I want to know why this loop isn't working so I can learn more about arrays and methods and so I'd know how to fix similar issues in the future.
For convenience:
public Form1()
{
InitializeComponent();
inputs[0] = textBox1;
inputs[1] = textBox2;
inputs[2] = textBox3;
inputs[3] = textBox4;
inputs[4] = textBox5;
numbers[0] = oneYear;
numbers[1] = twoYear;
numbers[2] = threeYear;
numbers[3] = fourYear;
numbers[4] = moreYear;
textBox6.ReadOnly = true;
for (int i = 0; i <= 4; i++)
{
inputs[i].KeyDown += (obj, args) =>
{
Keys[] allowedKeys = { Keys.Back, Keys.Next, Keys.Delete, Keys.Left, Keys.Right };
args.SuppressKeyPress = !allowedKeys.Contains(args.KeyCode) && (args.KeyValue < 48 || args.KeyValue > 57);
};
inputs[i].Text = 0.ToString();
}
}
private void autobots()
{
try
{
//find out why this doesn't work
for (int i = 0; i <= 4; i++)
{
if (inputs[i].Text == "")
numbers[i] = 0;
else
numbers[i] = Convert.ToInt32(inputs[i].Text);
}
/*if (textBox1.Text == "")
oneYear = 0;
else
oneYear = Convert.ToInt32(textBox1.Text);
if (textBox2.Text == "")
twoYear = 0;
else
twoYear = Convert.ToInt32(textBox2.Text);
if (textBox3.Text == "")
threeYear = 0;
else
threeYear = Convert.ToInt32(textBox3.Text);
if (textBox4.Text == "")
fourYear = 0;
else
fourYear = Convert.ToInt32(textBox4.Text);
if (textBox5.Text == "")
moreYear = 0;
else
moreYear = Convert.ToInt32(textBox5.Text);*/
oneTotal = oneYear * 24;
twoTotal = twoYear * 27;
threeTotal = threeYear * 30;
fourTotal = fourYear * 33;
moreTotal = moreYear * 36;
total = oneTotal + twoTotal + threeTotal + fourTotal + moreTotal;
textBox6.Text = total.ToString();
//label6.Text = ("$") + total.ToString();
}
catch
{
textBox6.Text = "";
//label6.Text = "";
}
}
Your for loop is working correctly....However, in order to shed some light on why this isn't working the way you need it to:
numbers[0] = oneYear;
numbers[1] = twoYear;
numbers[2] = threeYear;
numbers[3] = fourYear;
numbers[4] = moreYear;
When you do this you are storing the value of the variables into the array...not the variables themselves.
for (int i = 0; i <= 4; i++)
{
if (inputs[i].Text == "" || inputs[i] == null)
numbers[i] = 0;
else
here you set the value in the i position of the numbers array. to the value of whats in the text box. This does not change the value of your variables ("oneYear", "twoYear", etc..)
numbers[i] = Convert.ToInt32(inputs[i].Text);
}
but here you are are using the variables (ie "oneYear", "twoYear") which have not
had a new value stored in them. Remember the numbers[] array does not directly effect these variables
the numbers[] array (because it is an array of type int) only stored the values of these variables not a reference to the variables themselves. Because of this the code here does not do what you want it to.
oneTotal = oneYear * 24;
twoTotal = twoYear * 27;
threeTotal = threeYear * 30;
fourTotal = fourYear * 33;
moreTotal = moreYear * 36;
total = oneTotal + twoTotal + threeTotal + fourTotal + moreTotal;
textBox6.Text = total.ToString();
In order to get this code to work correctly you would need to use the values in the numbers[] array. Like this:
oneTotal = numbers[0] * 24;
twoTotal = numbers[1] * 27;
threeTotal = numbers[2] * 30;
etc...
When you do this it will output the correct results to textBox6.
The first section of code I pasted is only useful if the oneYear, twoYear, threeYear, fourYear, moreYear variables have a non-zero default value or have a value set before it ever gets to this code, and because you are using the numbers[] array to store the values from the text box you will not see the calculations you want to see, unless you use the numbers[] array values. Or if you're dead set on using the oneYear, twoYear... variables just use the if-else statments you have commented out, or put:
oneYear = numbers[0];
twoYear = numbers[1];
etc..
A little more clarification:
I think the reason you might have gotten a little confused here is because you are using two different types of arrays. A TextBox array used to store your textboxes, and an int array used to store the values in the text boxes. The TextBox array is storing objects...or a reference(pointer) to an object. So when you say inputs[0] = textBox1; you are telling the program to store the reference to textBox1 in the first element of the inputs[] array allowing you to directly manipulate the textBoxes stored in this array, but because the int type is a primary data type when it is stored in an array only its value is stored, not the variable itself.
Last thing:
You would need to create/use a wrapper class for your int variables in order to do what you are trying to do the way you are trying to do it.
I am trying to edit a line of a text file (.Hex file) containing all Hex characters without using pointers and in a more efficient way.
It takes so long because the program I have to edit some (around 30x4 bytes or 30 float values from the address values of hex file).
Every time the program replaces one byte, it searches the complete file and replaces the values, and copy back back again the new file to another file. This process repeats 30 times, which is quite time consuming and hence not looks appropriate.
What would be the most efficient method?
public static string putbyteinhexfile(int address, char data, string total)
{
int temph, temphl, tempht;
ushort checksum = 0;
string output = null, hexa = null;
StreamReader hex;
RegistryKey reg = Registry.CurrentUser;
reg = reg.OpenSubKey("Software\\Calibratortest");
hex = new StreamReader(((string)reg.GetValue("Select Input Hex File")));
StreamReader map = new StreamReader((string)reg.GetValue("Select Linker Map File"));
while ((output = hex.ReadLine()) != null)
{
checksum = 0;
temph = Convert.ToInt16(("0x" + output.Substring(3, 4)), 16);
temphl = Convert.ToInt16(("0x" + output.Substring(1, 2)), 16);
tempht = Convert.ToInt16(("0x" + output.Substring(7, 2)), 16);
if (address >= temph &&
address < temph + temphl &&
tempht == 0)
{
output = output.Remove((address - temph) * 2 + 9, 2);
output = output.Insert((address - temph) * 2 + 9,
String.Format("{0:X2}", Convert.ToInt16(data)));
for (int i = 1; i < (output.Length - 1) / 2; i++)
checksum += (ushort)Convert.ToUInt16(output.Substring((i * 2) - 1, 2), 16);
hexa = ((~checksum + 1).ToString("x8")).ToUpper();
output = output.Remove(temphl * 2 + 9, 2);
output = output.Insert(temphl * 2 + 9,
hexa.Substring(hexa.Length - 2, 2));
break;
}
else total = total + output + '\r' + '\n';
}
hex.Close();
map.Close();
return total;
}
Assuming you don't want to massively rewrite your existing logic which does 'for each line, do this search and replace logic', I'd think the simplest change would be:
var lines = File.ReadAllLines(filePath);
foreach (change to make)
{
for (int i = 0; i < lines.Length; i++)
{
// read values from line
if (need_to_modify)
{
// whatever change logic you want here.
lines[i] = lines[i].Replace(...);
}
}
}
File.WriteAllLines(filePath, lines);
Basically, you'll still do the logic you have now, except:
You read the file once instead of N times
you get rid of streamreader / streamwriter work
you do your changes on the array of strings in memory
string fileName = "blabla.hex";
StreamReader f1 = File.OpenText(fileName);
StreamWriter f2 = File.CreateText(fileName + ".temp_");
while (!f1.EndOfStream)
{
String s = f1.ReadLine();
//change the content of the variable 's' as you wish
f2.WriteLine(s);
}
f1.Close();
f2.Close();
File.Replace(fileName + ".temp_", fileName, null);