I need to build a form that allows a user to enter 100 different measurements. Then enter 100 different weights. I want to use the same text boxes. One for the measurements, one for the weights. Then have them store the value and then reset to accept the next value and so on. Can anyone point me in the right direction to accomplish this? I have searched for over an hour and can't find anything. Thank you in advance for your help.
When user clicks submit button, add to list or dictionary your value of both textboxes. Do this until wanted number of list.Count is reached. Let me know if I didn't understand your question right.
In WPF (C#) it would look something like this.
// Dictionary to save values
Dictionary<string, int> dict = new Dictionary<string, int>();
// Method that is called on user submit button click
private void HandleSubmit(object sender, EventArgs args) {
// Add values of both textboxes to dictionary
dict.Add(textBox1.Text, Int32.Parse(textBox2.Text));
// Check if all data is entered
// then activate custom method
if(dict.Count >= 100) {
CUSTOMMETHOD(dict);
}
}
-- EDIT --
#briskovich As I understood your comment. You want to save all 100 pressure samples first and then enter 100 weight samples. In that case there is no need to use dictionary, you could use two List<int> for pressure and weight. In that case, code would look something like this:
// Variables to save our data
// numberValues - number of values user needs to enter
// pressureList - list of entered pressure data
// weightList - list of entered weight data
int numberValues = 100;
List<int> pressureList = new List<int>();
List<int> weightList = new List<int>();
// Method that is called on user submit button click
// This method uses only one text box to input data,
// first we input pressure data until limit is reached
// and then weight data
private void HandleSubmit(object sender, EventArgs args) {
// Check if we are still entering pressure data, that
// is until we reach numberValues of pressure data values
// Same thing goes for weight list
if (pressureList.Count < numberValues) {
pressureList.Add(Int32.Parse(textBox1.Text));
}
else if (weightList.Count < numberValues) {
weightList.Add(Int32.Parse(textBox1.Text));
}
else {
// When we have #numberValues of values in both
// lists we can call custom method to process data
CUSTOMMETHOD(pressureList, weightList);
}
}
// Method for processing data
private void CUSTOMMETHOD(List<int> pressures, List<int> weights) {
// This loop will go through all values collected and
// will give you access to both pressure and weight on
// each iteration
for (int index = 0; index < numberValues; index++) {
int currentPressure = pressures.ElementAt(index);
int currentWeight = weights.ElementAt(index);
// Do processing here
}
}
Related
Console log
My list is adding the sprite name and converting it to an integer to add to a list, then I created a function to show the list but whenever I show the list in the update loop, it alternates between showing just 0's
and actual values. and when I don't put it in an update loop it only shows 0's
public class ballMove : MonoBehaviour {
int[] BallOrder = new int[5]; // me initializing the variable in the
beginning of the program
// int[] BallOrder = {4,6,3,2,7}; if I do this instead of showing 0's it
shows 4,6,3,2,7 when I click the mouse down.
void CreateBalls(int HowMany) {
// makes balls with a unique picture size and position
for (int i = 0; i < HowMany; i++) {
BallClone = Instantiate(Ball);
BallPic = BallClone.GetComponent<SpriteRenderer>();
// give each ball a random image, each image is a number
RandImg();
// just using i for testing purposes.
BallOrder[i] = i;
//array should just be 1,2,3,4,5
}
}
void ShowList()
{
System.Array.Sort(BallOrder);
string text = "";
for (int i = 0; i < BallOrder.Length; i++)
{
text = (text + " " + BallOrder[i]);
}
print(text);
}
void Update()
{
// here it shows the array correctly 1,2,3,4,5
ShowList();
}
void OnMouseDown() {
string BallNum = ConvertSprite(GetComponent<SpriteRenderer>().sprite);
int test = int.Parse(BallNum);
ShowList(); // here when I show list it just shows 0,0,0,0,0
Destroy(gameObject);
}
}
Just to give an answer to the question that is not in comments, the issue was that the console was printing out what could be considered bad data.
By alternating between what was expected (6 random numbers) and not expected (6 zeroes), clearly, the function was being called twice, but from further additions of code snippets, there was no reason as to why the function would be called multiple times.
From the initialization of the array data, the only way for there to be 6 zeroes instead of data was that the data was being overwritten or that it was never initialized. As the array is never written to again after the initialization, it must have meant that it was initialized incorrectly.
The only way for this to have occurred is by having the script attached to two objects in the scene where one is properly initializing the data and the other is not as the initialization occurred in Start.
The solution is to remove the unused script from one of the two objects in the scene.
I'm working on something for school, just a basic score calculator. I know it's not the prettiest code, but it works and that's more what the class is focused on here at the beginning.
The only issue that I have is that whenever I click "Display" it prints out 20 0s. 20 is the length of the array. Everything else is working. It adds the number I input into the array and replaces the 0s. But I don't want it to have 0s at all unless I specifically type them in.
Any help is appreciated.
Full code:
// Creates the list that displays the score
List<string> scoreList = new List<string>();
// Array to store up to 20 scores
int[] scoreArray = new int[20];
// class level variable to store current open slot in the array
int openSlot = 0;
public Form1()
{
InitializeComponent();
}
// Initializes variables that hold our math total and count of numbers entered
int total = 0;
int count = 0;
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void btnAdd_Click(object sender, System.EventArgs e)
{
if (openSlot <= scoreArray.GetUpperBound(0))
{
try
{
// Basic math for conversion of entered number and calculating total numbers entered
// and the averages of those numbers
int score = Convert.ToInt32(txtScore.Text);
total += score;
count += 1;
int average = total / count;
txtScoreTotal.Text = total.ToString();
txtScoreCount.Text = count.ToString();
txtAverage.Text = average.ToString();
txtScore.Focus();
}
catch(System.FormatException) // Makes sure that the user enters valid character into box
{
MessageBox.Show("Please enter valid number into box");
return;
}
// Adds the most recent entered number to the Score List
scoreList.Add(txtScore.Text);
}
// if statement to make sure that there is still room in the array to store the
// new entry
if (openSlot > scoreArray.GetUpperBound(0)) // GetUpperBound(0) returns the index of the last element in the first dimension
{
MessageBox.Show("The array is full! The most recent number was not added.");
txtScore.SelectAll();
txtScore.Focus();
return;
}
// Assigns a variable as an integer from the score text box
// to allow us to numerically sort the numbers in the scoreArray
int scoreParse = Int32.Parse(txtScore.Text);
// move the most recent number to the current open slot in the score array
scoreArray[openSlot] = scoreParse;
// add 1 to openSlot
openSlot += 1;
}
private void btnClear_Click(object sender, EventArgs e)
{
// Clears all input fields and resets variables to 0
openSlot = 0;
total = 0;
count = 0;
txtScore.Text = "";
txtScoreTotal.Text = "";
txtScoreCount.Text = "";
txtAverage.Text = "";
txtScore.Focus();
// Clears the array and list
int[] clearScoreArray = new int[20];
scoreArray = clearScoreArray;
List<string> clearScoreList = new List<string>();
scoreList = clearScoreList;
}
private void btnDisplay_Click(object sender, EventArgs e)
{
// If array has no stored values, display a MessageBox that informs user
if (scoreArray == null || scoreArray.Length == 0)
{
MessageBox.Show("There are no numbers to display");
return;
}
//move focus to the code textbox
txtScore.Focus();
// Creates a blank string variable named scr to input the scores into
// for the MessageBox
string scr = "";
foreach (var scoreAdded in scoreArray)
{
// Adds variable scr as the string to display
scr += scoreAdded + "\n";
}
// Sorts the array from lowest to highest number
Array.Sort(scoreArray);
// Displays a message box with the scores that were added
MessageBox.Show(scr);
}
}
When you declare a set amount of arrays (In your place it's 20), they get some sort of value, normally it's 0. Keep this is mind when you are using myArrayHere.length, cause it will check how many arrays have been declared (int[] array) and initialized (... = new array[]), not how many have been modified (given a value).
Best solution, IMO is creating a function, that would know how many elements in an array you will need or how many of them you are using (just have a function, that returns the amount of used variables, by checking it with a loop, and then modifying it later on... but that is one way to fix this issue, and there are better fixes than these I pointed out, but as I see you are newer to C# (prob.) fixing your issues with ok'ish code is good, as your first project should be meant for learning, later on, you can improve it and heck, if you are looking to become a pro, take some Programming courses on how to improve your code in general).
Good luck!
-Normantas
You can use nullable if you dont want zero as default value.
int? [] array = new int?[20] ;
Welcome to SO!
When an object is initially declared there is a default initialization value. In this case, 0 is the default value for an int in C#. The default value can often be changed at the initialization of the object if there's a supporting constructor.
When the int[] scoreArray = new int[20]; is declared, all 20 variables are assigned the value of 0. This is because C# does not allow uninitialized variables.
This link shows all default initialization values for C#.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table
Hi I am new to programming
I have a masked textbox into which a user inputs an account number, then I have a label which displays the number of users or rather display the number of times the account number has been changed. I.e. as each account number is being entered the customer count should increase.
I don't have an example code because I do not even know where to start
Please show me how to code this, I am using a form in Visual Studio
have it add the input to a list or array, and then you can run a check to see if the array/list contains that input already. If so, do not add the input again, if it does not, then add the input. You can then tell how many customers you have by the size of the list.
If you are taking in the users input as a string do a String Comparison or if you're doing strictly a numerical account number and am taking it in as an int then simply see if the numbers are different
For strings use:
result = input1.Equals(input2, StringComparison.OrdinalIgnoreCase);
For ints just use an If statement to test:
if(input1 != input2) {
Console.WriteLine("Input has changed")
else
Console.WriteLine("Input has not changed");
}
I'm guessing the user has to push a button after the user has entered the password? If so, we can easily track this. First we make a global int variable like so: private int userCount = 0;
Then we add an event to our button:
private void btnAccountNumber_Click(object sender, EventArgs e)
{
userCount = userCount + 1;
displayLabel.Text = userCount.ToString() + " Customers";
maskedTextBox.Clear();
}
So in this button we add our customer that just clicked on our button to the total of users.
Next we show that number in the label you created. And finally we clear the maskedTextBox of userInput so the next customer can use it.
I've stored a list of colors in my program. I am after an object in my scene to one of the colors in the list. So far, I have done the followings:
if(Input.GetKeyDown(KeyCode.O))
{
for(int i = 0; i < claddingColor.Count; i++)
{
claddingMaterial.color = claddingColor[i];
}
}
This isn't working due to a reason I know (and you can probably spot) but I lack to the verbal fortitude to write it down.
As opposed to have a multiple lines of the following:
claddingMaterial.color = claddingColor[0];
Each tied to different buttons, I like a way I can emulate the above but tie it to a single button press. Thus, if I hit the 0 button 5 times, it will loop through each color stored in the list. If I hit it for a sixth time, it will go back to the first color in the list.
Could someone please help me implement this? Or point me to something that I may learn how to do it for myself?
Define LastColor property as class member:
int LastColor;
In your function use modulo
if(Input.GetKeyDown(KeyCode.O))
{
claddingMaterial.color = claddingColor[(LastColor++) % claddingColor.Count];
}
Note: Depending on the type of claddingColor use Count for a List or Length for Array.
You won't need a for loop
int lastStep = 0;
if(Input.GetKeyDown(KeyCode.O))
{
claddingMaterial.color = claddingColor[lastStep++];
if (lastStep == claddingColor.Count)
lastStep = 0;
}
I have a list that contains file names like f1, f2, f3,...,f6. my
program needs to output a list with file names appearing in
random order such as f4,f1,f6,f2,f3,f5.
I want to swap or shift string correctly inside a list I have a list of
size 6 named fileName already containing 6 different file names I
am swapping file names inside of a list fileName as follows and fil
is also a string for remembering current string or file name.
temp =-1;
foreach (Control control in tableLayoutPanel1.Controls) // run loop untill every control inside tablelayoutpanel1.Controls is check or read
{
Button btns = control as Button; // btn sotre the
current button in table.contr
if (btns != null) // check btn got a button from
the panel then
{
temp++;
int randomNumber = 0;
randomNumber = theArray[temp]; //this pic the random number from 0 index then 1 so on theArray already contains random number from 0 to 5 without any repitition and also tested
fil = fileName[randomNumber]; //fil for holding string
fileName[temp] = fileName[randomNumber]; // at filname[0]
swap or shift filename[randomNumber] random are between 0 to
5 and without repitition
fileName[randomNumber] = fil; // this line isnt even necessary
but to be safe i wrot
btns.BackgroundImage = images[randomNumber]; // change
btn image to current random image
copyImages.Add(images[randomNumber]);
btns.BackgroundImage = null; // i purposely doing this :)
}
Using that code I am able to swap string but I cant swap them
correctly as it only run for 6 times so it should swap 6 strings
(each with different name) inside the list on 6 different location
inside the list fileName but its not happening some strings are
showing twice or thrice, hoping someone can point out what I am
doing wrong and theres no index out of range or exception error
I tested it for like hundred time please help thanks and any idea
suggestion or piece of code will be helpful and fil just storing the string at the location of fileName[temp] :) and temp just going from 0 to 5 in a loop
i dont want to shuffle them i just want to swap them according to given index which i am doing in my code but cant to it properly theArray already contains the suffle index i just want to assign the fileName[0] index to theArray[temp] i can send you my proj if you want to have a look just send me hi to my id which show in my profile
So given you have a List of length 6 and an int[6] containing 0 to five in random order
List<String> newList = newList<String>();
foreach(int position in theArray)
{
newList.Add(filename[pos]);
}
filename.Clear();
fileName.AddRange(newList);
would be one way.
or you could simply do filename = newList and not bother with the Clear and AddRange.
You stored the wrong String in your temporary variable.
fil = fileName[temp]; // index changed here
fileName[temp] = fileName[randomNumber];
fileName[randomNumber] = fil;
This is a simple way to shuffle elements in an array. Basicly you go through the array from one end to the middle, swapping each element with one selected at random. Since each swap operation results in two elements being randomly placed, when we reach the middle, the whole array is shuffled.
void Main()
{
var arr = new string[] {"a","b","c"};
Shuffle(arr);
// arr is now shuffled
}
public static void Shuffle<T>(T[] arr)
{
Random r = new Random();
for(int i = arr.Length; i > arr.Length / 2; i--)
{
Swap(arr, r.Next(i), i -1);
}
}
private static void Swap<T>(T[] arr, int first, int second)
{
T temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}