I am working on a text-based game, and I want to print the results in the end.
However, at the moment it only prints the latest input data and not the 5 loops in the array.
This is my array
int[] turnarr = new int[5];
turnarr[x] = turn;
for (int i = 0; i < turnarr.Length; i++)
Console.WriteLine(turnarr[i] + "\t" );
It's hard to be certain, as I only see part of the code, but I suspect that you are recreating the turnarr array in each turn, which would make every entry except the last one zero.
If the value of x never changes then you're only writing to a single item in the array, and thus overwriting it every time with the latest value of turn.
If turn is your last turn value, and x is 4, you will see four zeroes on their own lines and then the value of turn because you are only assigning to the xth index of turnarr
I took a look at your pastebin and tracked the issue down I believe:
The following line:
Console.WriteLine(turnarr[i] + "\t" + windarr[i] + " ms \t" + apmeterarr[x] + "m\t\t" + lenghtarr[x] + " meter\t\t");
you are using i for 2 spots, and x for the other 2 for your index variable...
Change
apmeterarr[x] and
lenghtarr[x]
To
apmeterarr[i] and
lenghtarr[i]
Related
For this, I'm deriving code from a text file as strings, and I want to count the frequency of each of the strings. I got the counter to loop, but if the counter will display the result multiple times.
How do I get it to recognize unique strings?
I want it to display this:
The number 1 appears 1 time
The number 2 appears 4 times
The number 4 appears 3 times
But it's displaying this right now:
The number 1 appears 1 time
The number 2 appears 4 times
The number 2 appears 4 times
The number 2 appears 4 times
The number 2 appears 4 times
The number 4 appears 3 times
The number 4 appears 3 times
The number 4 appears 3 times
void Start()
{
string Random = "";
// Read text
string Numbers_Path = Application.dataPath + "/Text_Files/Numbers.txt";
string[] Duplicates = File.ReadAllLines(Numbers_Path);
foreach (string number in Duplicates)
{
Random += number;
}
//output display text_file
NumOutput.text = Random + "\n";
Array.Sort(Duplicates);
for (int x = 0; x < Duplicates.Length; x++)
{
count = Duplicates.Count(n => n == Duplicates[x]);
Display += "The number " + Duplicates[x] + " appears " + count + " time/s" + "\n";
}
Results.text = Display;
You could use Enumerable.GroupBy to group the lines by the value(text value should be sufficient here). For example,
foreach(var number in Duplicates.GroupBy(x=>x))
{
Console.WriteLine($"The number {number.Key} has appeared {number.Count()} times");
}
Breaking the solution into parts,**
Step 1 : Input read from Text File
var Duplicates = File.ReadAllLines(Numbers_Path);
Step 2 : Grouping the Duplicate Collection by Value
Duplicates.GroupBy(x=>x)
Ouput : Final Result
The number 1 has appeared 3 times
The number 2 has appeared 2 times
The number 3 has appeared 3 times
The number 5 has appeared 2 times
You're looking for either Distinct (reduces to just the unique elements) or GroupBy (divides into groups by some criteria).
See the LINQ reference for more details.
For example, using the latter could look like:
var counts = Duplicates
.GroupBy(x => x) // We're grouping by uniqueness, so use the entire value
.Select(g => $"{g.First()} appears {g.Count()} times");
Results.text = string.Join("\n", counts);
If you do not need them in the original order for any other reason, you could use a Dictionary<string, int>.
If you got a string from the file, you check if it is already in the collection - and if so, increase the value by 1. If not, you add it to the collection with a value of 0. And you can do all that while reading the file, possibly even using a Enumerator to go over the lines.
I would also not worry about performance. Dictionary<Key, Value> is also the generic HashTable internally - so the string comparison will usually not be necessary during search and addition. And on top of that, strings are immutable and can be interned.
So the logic would probably go:
Hash comparison
Reference comparison
Actually going of those chars
This if statement within the update() have 2 for-loop, but it only runs the first one after the if condition is activated, and I don't know why.
I'm building a code for path optimizing in unity. Currently I have to find out the path that came across the nodes/points/positions with a certain positions array that the index is the order the path should follow. Some path between 2 nodes are repeated , ex: A to B and B to A is consider the same path and shall thicken the width of line AB eventually rendered. So I tried to sort out the position array into 2 different array for comparing if any of the pair of nodes(or we can say line) is repeated. And I encountered a problem in if statement within the update().
The first should sort out the original array for later comparison. The second one is just for testing if the first one do their job. No comparing yet. However after hitting play and satisfy the if statement I can see all the Debug.log in the first one, everything is normal, the sorting is normal, while the second one just doesn't print anything at all.
I tried comment out the first one, and the second one will run.
I tried to put second one outside the if statement, after it, and without commenting the first one, the second one won't run.
I tried to put the second one before the first one, in the if statement, the second one will run and the first one won't.
So I think this might be some kind of syntax error or am I using the if statement wrong? Please help.
if (l > 0)//activate when we choose any preset processes
{
for (int n = 0; n <= positions.Length; n++)//this loop will sort all the pos1 and pos 2 into array for current frame
{
curPos_1 = positions[n];//current position of node 1
curPos_2 = positions[n + 1];
Debug.Log("CURPOS_1 of line number " + n + " is " + curPos_1);
Debug.Log("CURPOS_2 of line number " + n + " is " + curPos_2);
flag[n] = 0;
Pos_1[n] = curPos_1;
Pos_2[n] = curPos_2;
Debug.Log("POS_1 array of line number " + n + " is " + Pos_1[n]);
Debug.Log("POS_2 array of line number " + n + " is " + Pos_2[n]);
}
for (int o = 0; o <= positions.Length; o++)
{
Debug.Log("flag of number " + o + " is " + flag[o]);
}
}
As described, all for loop should print something. Not just one of it.
Have you checked your Unity Console Window ?
In your first loop you get the next item but its condition will fail at the end, i.e. off by one.
Correct code should be something like this:
var floats = new float[100];
for (var i = 0; i < floats.Length - 1; i++)
{
var f1 = floats[i];
var f2 = floats[i + 1];
}
Now, Unity, has a behavior of ON ERROR RESUME NEXT, so it's highly probable that an error has occured but you haven't seen it (did you turn off the red icon for toggling errors in console ?).
Also, for some conditions only you know about (you didn't post the whole context), it could work once after you've changed some state of your program.
I am learning C# and I came to this "for" function and something really bothers me about it:
int[] arrayNumbers = new int[numberAmmount];
// take "numberAmmount" as 5 so numberAmmount = 5;
for (int i = 0; i < numberAmmount; i++)
{
Console.Write("{0} Number: ", i + 1);
numberAmmount[i] = int.Parse(Console.ReadLine());
}
Isn't "i++" in for function the same i as in the Console.Write "i + 1"
Shouldn't i after the first cycle be 2?
and after the second cycle be 4 because of the i + 1 in console.write???
Basically I am trying to get in a number from the user which will be the amount of numberAmmount and by this for function i give every numberAmmount[x] a value and then have my program decide the highest and the lowest number but I don't understand why the i + 1 doesn't add an extra 1
edit: got it thanks
The syntax i + 1 does not have an assignment operator. That code is printing the value of i plus a constant. So when your loop is looping from 0...n Console.write is printing the counting value of each loop 1...n+1.
I had three values (Name, Course and Average) which were assigned to 3 arrays. I had to combine them and put them in a listbox. Now, I need to be able to select the same line and break it back up into the 3 variables.
My listbox output looks like this:
Lastname, firstname SEC360 93.5
I tried to do a split with space, but that breaks up my lastname and firstname, which need to be one combined variable with the comma included (I need to check it against the array in which it is placed). I cannot do substring either, because I do not have a set value. Any ideas?
EDIT:
I am sorry everyone. Im a inexperienced programmer (to say the least) and new to this site.
This is where I loaded the arrays:
studentNamesAr[studentCount] = studentNameTxtBox.Text;
courseAr[studentCount] = courseNumTxtBox.Text;
gradesAr[studentCount, 0] = Convert.ToInt32(grade1TxtBox.Text);
gradesAr[studentCount, 1] = Convert.ToInt32(grade2TxtBox.Text);
gradesAr[studentCount, 2] = Convert.ToInt32(grade3TxtBox.Text);
gradesAr[studentCount, 3] = Convert.ToInt32(grade4TxtBox.Text);
This is where I load the arrays to the listbox:
for (int i = 0; i != studentCount; i++)
{
studentAvg = ((gradesAr[i, 0] + gradesAr[i, 1] + gradesAr[i, 2] + gradesAr[i, 3]) / 4);
studentListBox.Items.Add(string.Format("{0, -20} {1, 20} {2, 20:F1}", studentNamesAr[i], courseAr[i], studentAvg));
}
Yes this is Windows Forms.
Data is not lost in arrays. When the program runs I should have maybe 5 entries. I need to split them back up so that when I select one from the listbox (to delete it), I will find the values in the 3 arrays and delete them, and then shift the remaining array values up.
If you preserve the order of your items in the listbox, the SelectedIndex of the listbox should match up with the indices from your original arrays. So once you have that, you can go about shifting your arrays up (which is pretty tedious).
For the record, there are much better constructs to use to approach this problem, but I'm assuming the stipulation of using arrays is part of a homework assignment. :)
You could hold the value separated by some other delimiter in the .Tag property.
I suggest you to replace the ", " (notice the space after the ',') with something else (like ";") then use the split method with space as the parameter.
string s = "Lastname, firstname SEC360 93.5";
string[] result = s.Replace(", ", ";").Split(' ');
then you may change back the result[0] by replacing ";" with ", "
I have a List Box with different Cakes in them. How do I give each cake a price and have my label display the total cost of the selected cakes? The following is the code I have so far.
for (int index = 0; index < lstCakes.SelectedItems.Count; index++)
{
strCakes += Environment.NewLine + lstCakes.SelectedItems[index].ToString();
}
double tax = 1.13;
lblOrdered.Text = "You have ordered: " + strCakes + '\n' + "Total Cost: " + (tax * cakeCost).ToString("C");
I tried using switch like the following but that only shows the cost of the last selected item.
switch (lstCakes.SelectedIndex)
{
case 0:
if (lstCakes.SelectedIndex == 0)
{
cakeCost = 18;
}
break;
case 1:
if (lstCakes.SelectedIndex == 1)
{
cakeCost = 25;
}
break;
case 2:
if (lstCakes.SelectedIndex == 2)
{
cakeCost = 40;
}
break;
case 3:
if (lstCakes.SelectedIndex == 3)
{
cakeCost = 30;
}
break;
}
Any suggestion are appreciated.
Assuming that this is a desktop application, you will probably want to put your prices in a config file so that they can be changed later. You add an <appSettings> block to your App.config file with an entry for each cake and then use the ConfigurationManager.AppSettings[] command to retrieve them.
So if this is a Windows Forms app, then on the form load you can go into your app settings, retrieve the details for all the cakes that you want and then populate your list box with entries for each one (see http://msdn.microsoft.com/en-us/library/z38x31c0.aspx). This way you can dynamically create the text for each entry. If you want each line to contain the price you are going to have to hardcode it into the line's text. (I think that is what you are asking...)
One final note. You shouldn't use + to concatenate strings. Strings in C# are immutable -- that means that the string itself cannot be modified (the reason why is a whole other topic that I can explain if you wish). In order to concatenate two strings with "+", C# needs to create a third string and fill it with the contents of the first two, and this drains performance. To concatenate strings more efficiently, use either a StringBuilder object and the Append() method, or use String.Format() which works the same way.
Immutable strings:
Strings at their core are arrays of characters. Just as you cannot resize an array, you cannot resize a string. This is because arrays are stored on the stack... the stack is a piece of memory which is filled with instructions to run your program that are all "stacked" on top of each other. Stack memory is pre-allocated and for all intents and purposes you cannot dynamically change the memory footprint of objects on the stack. You can have an array of 10 ints containing 5 ints and 5 empty spaces, but you cannot take an int[5] and change it to an int[10]. If you want to add 5 more ints to an int[5] you need to instantiate a new int[10] and fill it up. The same thing goes for a string.
The solution to the array resizing problem is dealt with using Lists and their derivatives. They function using heap memory. This is similar to how a StringBuilder object functions. If you want to know more about stack and heap memory and how it affects how your program runs, this might help you understand a bit better http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx. It is really important to know, because it can explain a lot of mysteries that will stump beginner programmers. Good for you for asking.
The cake prices could be maintained on a Enum
enum CakePrices{
ChocCake = 20,
VanillaCake = 50
}
Calculate the Cost:
int TotalCost;
for (int index = 0; index < lstCakes.SelectedItems.Count; index++)
{
strCakes += Environment.NewLine + lstCakes.SelectedItems[index].ToString();
//The name of the List Items should match the names on the enum,for this to work
TotalCost += (int)Enum.Parse(typeof(CakePrices),
lstCakes.SelectedItems[index].ToString() ,
false)
}
Console.WriteLine("You have ordered:" + strCakes + '\n' + "Total Cost: " + TotalCost);