there are a couple of these questions asked, but mine primarily involves Windows Forms, which there are few, although if there is an answer, a relatively well explained one without complicated jargon please let me know so I can learn from it.
Cutting to the chase: I want to read some data from a txt file into an array and then display it into some radio buttons. But for here I have simplified it and put them into a messagebox.
private void Game1_Load(object sender, EventArgs e)
{
const int iGAME = 4;
string[] sQuestions = new string[iGAME];
int iNum;
using (StreamReader sr = new StreamReader("questions.txt"))
{
for (iNum = 0; iNum < iGAME; iNum++)
{
MessageBox.Show(sQuestions[iGAME]);
}
}
The problem here is that the system tells me that the index exceeds the bounds. Now I have checked the txt file and there is definitely 4 pieces of information to apply to an array.
You're using the wrong index for the array. You're passing iGAME (a constant set to 4) when you should be using iNum (a variable between 0-3). Given that the upper-bound for the index is 3, the 4 will cause the ArrayIndexOutOfBoundsException.
Also, tip: C# is not C, so you don't need to use separate constants to denote the length of an array, also convention in C-style languages is to use just i as an index variable, and it avoids confusion between iGAME and iNum which has befallen you. Finally, avoid including the type-name in a variable's name, you don't need it anymore, this isn't the 1980s with Hungarian notation. You can rewrite your code to be more maintainable as:
String[] questions = new String[ 4 ];
for(int i=0; i<questions.Length; i++) {
...
}
Or just use this:
String[] questions = File.ReadAllLines( fileName );
foreach(String question in questions) MessageBox.Show( question );
I dont get what you want but first
MessageBox.Show(sQuestions[iGAME]) is wrong
change it to
MessageBox.Show(sQuestions[iNum ]);
I have managed to fix my code, to those that are doing a similar sort of thing to me here is my fix, hope it helps you:
int i;
using (StreamReader sr = new StreamReader("questions.txt"))
{
for (i = 0; i < Questions.GetLength(0); i++)
{
MessageBox.Show(Questions[i] = Convert.ToString(sr.ReadLine()));`
What I did here is state the loop variable i, using StreamReader to read the TXT file (don't forget to add using System.IO; at the top of the page. I then created a for loop so that it saves time by assigning each array with data. I then decided to show the results in a messagebox for simplicity by stating the Questions with the array counter [i] and then converted it to a string so it could be read in the box as before hand it was just blank.
Hopefully that little friendly walkthrough helps you solve your issue.
Related
I am just beginning with programming in c#;
I got a list of int variables that I want to sort, and find the number 1.
int Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9
do I need to do this with an array?
By using the yellow book of C# I found out how to make an array, but I can't figure out how to assign the variables to the array.
int [] Weapon_Count = new int [11] ;
for ( int i=0; i<11; i=i+1)
{
Weapon_Count [i] = ??? ;}
I hope this does make sense..
Please let me explain how to use a C#-array.
This creates an unitialized integer-array with 5 elements:
int[] a1= new int[5];
Assigning values 9,8,7,6 and 5:
(Please note that only indexes from 0 to 4 can be used. Index 5 is not valid.)
a1[0]=9;
a1[1]=8;
a1[2]=7;
a1[3]=6;
a1[4]=5;
The same can also achieved with just one line:
int[] a1= new int[] {9,8,7,6,5};
This might help you.
// Declaring the array
int[] Weapon_Count;
// Initializing the array with a size of 11
Weapon_Count = new int[11];
// Adding values to the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Weapon_Count[i] = i + 100;
}
// Printing the values in the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Console.WriteLine(Weapon_Count[i]);
}
// Same thing with a list
// Daclare and initializing the List of integers
List<int> weapon_list = new List<int>();
// Adding some values
weapon_list.Add(1);
weapon_list.Add(2);
weapon_list.Add(3);
weapon_list.Add(4);
weapon_list.Add(5);
// Printing weapin_list's values
for (int i = 0; i < weapon_list.Count; i++)
{
Console.WriteLine(weapon_list[i]);
}
// This is just for the console to wait when you are in debug mode.
Console.ReadKey();
Dont forget to include the using statment if you want to use lists (in short hand - dynamic arrays that can change in size.)
using System.Collections.Generic;
The easiest way to do this, assuming there is a finite list of variables to check, would be to throw them into a temporary array and call either Max() or Min() from the System.Linq namespace.
int maxCount = new int[] { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 }.Max(); // or .Min()
EDIT
If you still want to get those variables into an array, I would recommend using a System.Collections.Generic.List which has a dynamic size and helper methods such as .Add() to simplify things. Lists can also be used with Linq functions similar to the first part of my answer. See Dot Net Perls for some really good examples on different C# data types and functions.
EDIT 2
As #kblok says, you'll want to add using System.Linq; at the top of your file to gain access to the functions such as Max and Min. If you want to try using the List type, you'll need to add using System.Collections.Generic; as well. If you're in Visual Studio 2017 (maybe 2015 as well?) you can type out the data type and then hit Ctrl + . to get suggestions for namespaces that might contain that data type.
Before we start, you might edit your array to look like this:
int[] weapons = { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 };
This means that you've created an array called weapons and it is holding integer values.
After you did this, lets find out which element in your array has value of number one.
To find which value has value "1" we must look at each element in array, and we might do that on few ways but I would like recommend foreach or for loop, in this case I will choose foreach loop.
foreach(var item in weapons)
{
if (item == 1)
//Do something
}
This above means, loop throught all of my elements, and in case some of them is equal to number one please do something..
P.S
(I may advice to create one variable which will hold an element which has value '1' and when you find it in a loop assing that variable to that element, and later you can do whatever you want with that variable.. and if you think there will be more elements with value of number one and you need all of them, instead of variable I mentioned above you will create list or array to hold all of your elements and also you can do later with them whatever you want to.)
Thanks and if you are interested in this kind of solution, leave me a comment so let me help you till the end to solve this if you are still struggling.
following problem in C# (working in VS Community 2015):
First off, i fairly new to C#, so excuse me if that question would be an easy fix.
I have a contact sensor giving me a string of numbers (length measurement). I read them with the SystemPort Methods and cut them down to the numbers that i need with substring (as the beginning of the string, the "SR00002" is useless to me).
In the end i end up with a string like : "000.3422" or "012.2345". Now i want to convert that string to one solid int-variable that i can work with, meaning subtract values from and such.
Bsp: I want to calculate 012.234 - 000.3422 (or , instead of . but i could change that beforehand)
I already tried Parse and ConvertToInt (while iterating through the string) but the endresult is always a string.
string b = serialPort2.ReadLine();
string[] b1 = Regex.Split(b, "SR,00,002,");
string b2 = b1[1].Substring(1);
foreach (char c in b2)
{
Convert.ToInt32(c);
}
textBox2.Text = b2 + b2.GetType();
I know that when b2 will be int it can not be printed in the Textbox but ill take care of that later.
When everything is converted accordingly, ill outsource the conversion to its own method =)
The GetType is just for testing and as said shows only System.String (which i dont want). Help would be much appreaciated. I also browsed the searchfunction and google but couldnt find anything of help. I wish any possible helpers a nice day, mfg Chris.
use the int.Parse
int.Parse("123")
You need to assign the converted values to a new variable or array that takes int or other numeric values that you want.
int[] numbers = new int[b1.length];
for(int i = 0; i < b2.length; i++)
{
numbers[i] = Convert.ToInt32(b2[i]);
}
I have the following code but it takes 20sec to process the 52957 inputs of type BigInteger. This is the question that i want to solve https://www.hackerearth.com/problem/algorithm/girlfriends-demands/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace girldfriends_demands
{
class Program
{
private static string inputString = String.Empty;
private static int testCases=0;
private static BigInteger[,] indexArray;
static void Main(string[] args)
{
initialize();
printDemand();
Console.ReadLine();
}
private static void initialize()
{
inputString = Console.ReadLine();
testCases = int.Parse(Console.ReadLine());
indexArray = new BigInteger[testCases, 2];
for (int i = 0; i < testCases; i++)
{
string[] tokens = Console.ReadLine().Split();
indexArray[i, 0] = BigInteger.Parse(tokens[0]);
indexArray[i, 1] = BigInteger.Parse(tokens[1]);
}
}
private static void printDemand()
{
char[] convertedString = inputString.ToCharArray();
for (int i = 0; i < testCases; i++)
{
BigInteger length=inputString.Length;
BigInteger startf, endf; ;
BigInteger.DivRem(indexArray[i, 0] - 1,length,out startf);
BigInteger.DivRem(indexArray[i, 1]-1,length,out endf);
char c=convertedString[((int)startf)];
char e=convertedString[((int)endf)];
if(c==e)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
}
}
Please specify how to reduce the time complexity of the code.This program gets the letters at the specified position in a string and prints true if they are same else false. Also computing the range at prior to the loop isn't helping
Why you use BigInteger ?
In any case string.length is typeof int.
It mean that if your string exceed 2147483647 (2^31 -1) your program will be broken.
I think changing BigInteger to int will help.
Console.ReadLine().Split()
is the biggest of your problems. For every single line in the file, you create an array of strings, one letter per string. This is a huge performance drain, and almost certainly not what you intended - in particular, it would be wholy unnecessary to use BigInteger to store a single-digit number...
I assume that you actually want to split the line in two based on some delimiter. For example, if your numbers are separated by a comma, you can use
Console.ReadLine().Split(',')
Even then, there is little reason to use BigInteger at all. The operation you're trying to perform is distinctly string-based, and very easy to do with strings. However, I can't really help you more specifically, because your problem description is incredibly ambiguous for such a simple task, and the code is so obviously wrong it's entirely useless to guess at what exactly you're trying to do.
EDIT:
Okay, your link confirmed my assumptions - you are massively overcomplicating this. For example, code like this will do:
var word = Console.ReadLine();
var items = int.Parse(Console.ReadLine());
for (var _ = 0; _ < items; _++)
{
var indices =
Console.ReadLine()
.Split(' ')
.Select(i => (int)((long.Parse(i) - 1) % word.Length))
.ToArray();
Console.WriteLine(word[indices[0]] == word[indices[1]] ? "Yes" : "No");
}
First, note that the numbers will always fit in a long, which allows you to avoid using BigIntever. Second, you need to use Split properly - in this case, the delimiter is a space. Third, there's no reason not to do the whole processing in a single stream - waiting for the whole input, collecting it in memory and then outputting everything at once is a waste of memory. Fourth, note how easy it was to avoid most of the complex checks while incorporating the whole necessary mechanism in simple arithmetic operations.
This runs under 2 seconds on each of the input data, only using ~80kiB of memory.
I think that ideologically, this fits the site perfectly - it's very simple and straightforward and works for all the expected inputs - the perfect hack. Of course, you'd want extra checks if this was for an end-user application, but the HackerEarth site name implies hacks are what's expected, really.
In my experience, frequent Console.WriteLine calls can lead to huge execution times.
Instead of calling that function whenever you want to add some output, I think you should use a StringBuilder object, and append all your output to it. Then, after the for-loop, call Console.WriteLine once to print the StringBuilder's contents.
This might not be your program's biggest problem, but it will help quite a bit.
Myabe by removing casts in these line and using string.compare you cand decrease execution time
if(string.Compare(startf.ToString(), endf.ToString()))
{
Console.WriteLine("Yes");
continue;
}
Console.WriteLine("No");
This question already has answers here:
Most efficient way to append arrays in C#?
(11 answers)
Closed 8 years ago.
Background on the program: the heart of the program needs to track all other Forms or other elements of the program. To do this, I am using a Form array
What I am wanting to do is take my initially defined array containing 1 element, and increase the length of the array to add a new element whenever a new Form is launched.The trouble I've run into is that I can't find out how to do this without using a second array to store the old array, re-declaring the original array with array.length += 1, looping through to re-add the original content from the second array, then adding the new element. It's heavy and inconvenient since I need to use similar processes elsewhere.
The code I have, which works but is ugly, is this:
public class PCB
{
Form[] Runners;
public PCB()
{
Runners = new Form[1];
Runners[0] = new GUI;
.
.
.
.
.
void NewForm(Form app)
{
Form[] TEMP = Runners; //Create my new array equal to the first
Runners = new Form[Runners.Length + 1]; //re-create the old array, with an additional element
for (int k = 0; k < TEMP.Length; k++)
{
//add the original elements back to the original array
Runners[k] = TEMP[k];
}
Runners[TEMP.Length] = App; //add the final element to the array
I hate having to use the loop-structure, as I feel that it can be done cleaner. what I'm looking for is a function similar to the ListBox.Items.Add([[ITEM]]), but for an array.
Does such a function exist, or do I need to continue with my ugly loops?
Use a list instead:
List<Form> Runners = new List<Form>();
...
Runners.Add(app);
If you for some odd reason absolutely must use an array, then Array.Resize is what you're looking for, but a list is much better.
I believe what you're looking for is a List. A List already does this for you under the hood in .NET. You can do this:
List<Form> Runners;
Runners = new List<Form>();
Now when you add to the list you can do:
Runners.Add(new MyForm());
When you want to remove from the list you can do:
Runners.Remove(MyForm);
Just use a List<Form> list instead of arrays, which can be accessed just like an array and you can dynamically add other elements (list.Add(new Form(...))).
It is much more performant than an array and it has other features that can simplify your coding.
One way is to use Array.Resize
P.S. !!! be sure that the references to your array won't be changed.
Here is an example:
using System;
class aaa
{
static void Main()
{
string[] array = new string[10];
Array.Resize(ref array, 20);
}
}
I am trying to take the values in the textboxes, named sequentially from 0-9, and add that to a List using a for loop. I am having problems with the syntax or something.
here is what I have now.
for (int i = 0; i <= amt.Count(); i++)
{
amt[i] = int.Parse(amtBox[i].Text);
}
The error is that amtBox doesnt exist in the current context.
My problem is within the loop where i have amtBox[i].Text. I have tried this several ways and VS always throws an error. I have tried "amtBox" + i and that compiles but then causes an error when I try to do something with it and says "data is of wrong type".
I am new to C# and come from PHP so maybe that is why I think this approach will work. PHP doesnt care about data types where C# really does. I have done this exact thing in PHP many times without any issue.
Any suggestions on another way to do this are appreciated as I am probably coming at this all wrong.
Thanks
One solution would be to declare an array and assign amtBox'es to the individual indexes in the array and then you can iterate on that array.
var amtBoxes = new TextBox[] { amtBox0, amtBox1, .... };
for (int i = 0; i <= amt.Count(); i++)
{
amt[i] = int.Parse(amtBoxes[i].Text);
}
If you end up needing to iterate on your TextBox controls in other places I would consider making the array an instance member of your object.
I suppose that your textbox are named "amtBox" + a number.
(The Name property is "amtBox1" as an example)
In this case you could use
Control[] t = Controls.Find("amtBox" + i, false);
for a code like this
for (int i = 0; i <= amt.Count(); i++)
{
Control[] t = Controls.Find("amtBox" + i, false);
if(t != null && t.Length > 0)
{
amt[i] = int.Parse(t[0].Text);
}
}
My understanding is that you have text boxes named amtBox1, amtBox2, etc., and what you are trying to do is sequence through them. As you point out, this is very easy in PHP. It is possible to do what you're suggesting using reflection, but that is expensive and, in any event, there's probably a better way to do what you're looking for.
You could put all of your amount boxes into an array, and then what you have would work:
var amtBoxes = new[] {
amtBox1,
amtBox2,
amtBox3
}