This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I'm creating a quick project which takes a .txt from the user, saves each line to an array and then makes a request for each ID, depending if the response contains 'The profile could not be found', or a valid profile, act accordingly.
Here's my code;
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\\users\\louis\\Desktop\\d.txt");
string[] avaliableIds = { };
string errorMessage = "The specified profile could not be found.</h3><br><br>";
foreach (string c in lines)
{
WebRequest req = WebRequest.Create("http://steamcommunity.com/id/" + c);
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returne = sr.ReadToEnd();
System.Threading.Thread.Sleep(100);
if (returne.Contains(errorMessage))
{
int avaliableArrayLength = avaliableIds.Length;
int shouldGo = avaliableArrayLength + 1;
avaliableIds[shouldGo] = c;
} // Here is where I'm getting the error
}
for(int i = 0; i == avaliableIds.Length; i++)
{
Console.WriteLine(avaliableIds[i]);
}
}
From what I understand, 'shouldGo' has a higher value than 'avaliableIds', so something is wrong with my declaration, it's supposed to be an array which can hold as high as or as low any number possible.
Please help, thanks.
In C#, arrays have a fixed size. You declare availableIds as an empty (zero-length) array, so you won't be able to store any data in it.
Use a List<string> instead, that's a variable-size data structure.
i == avaliableIds.Length
should be
i < avaliableIds.Length
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
So e (this is not a question of what a index out of range exception it is why this specific one is happening when Im using the same index and method some where else Response to recent mark of repetition)
Essentially I am checking to see if a value in the array is Null. But it
keeps giving me an out of range exception when I just used the same
principle
in another area. This may be a silly question with a silly answer but I've
run into the issue and I seem to not be able to solve it.
I have checked that the int going in is correct and that the array is the
correct size.
Im sorry for lack of highlights Im new here and am not sure how to apply
them.` The Place where it goes Wrong
public void OnDragStop()
{
if (SlotHover.name.Contains("Slot"))
{
string[] OS = PSlot.name.Split('t');
int PSN = int.Parse(OS[1]);
string[] NS = SlotHover.name.Split('t');
SN = int.Parse(NS[1]);
Debug.Log(SN);
if (inventory.Inventoryitems[SN] == null)
{
inventory.Inventoryitems[SN] =
inventory.Inventoryitems[PSN];
inventory.Inventoryitems[PSN] = null;
SlotHover.transform.Find("ItemSlotSprite" +
SN).GetComponent<Image>().sprite =
PSlot.transform.Find("ItemSlotSprite" +
PSN).GetComponent<Image>().sprite;
PSlot.transform.Find("ItemSlotSprite" +
SN).GetComponent<Image>().sprite = EmptySprite;
this.gameObject.transform.position = PP;
}
}
}
The Place where its working
public void AddItem(Item ItemToAdd)
{
for(int i = 0; i < inventory.Inventoryitems.Length; i++)
{
if(inventory.Inventoryitems[i] == null)
{
inventory.Inventoryitems[i] = item;
Sprite sprite = ItemToAdd.DefualtSprite;
Inventory.transform.Find("Slot"+i).transform.Find("ItemSlotSprite" +
i).GetComponent<Image>().sprite = sprite;
return;
}
}
}`
IndexOutOfRange: Array index out of range
is what it gives me as shown above Im not sure why in this specific case
its giving the exception.
I think you need to check inventory lenght
if(inventory.Inventoryitems.Length >0){
for(int i = 0; i < inventory.Inventoryitems.Length; i++)
{
if(inventory.Inventoryitems[i] == null)
{
inventory.Inventoryitems[i] = item;
Sprite sprite = ItemToAdd.DefualtSprite;
Inventory.transform.Find("Slot"+i).transform.Find("ItemSlotSprite" +
i).GetComponent<Image>().sprite = sprite;
return;
}
}
}
This question already has answers here:
What's the fastest way to read a text file line-by-line?
(9 answers)
Closed 5 years ago.
So I am just starting out C# with little to no knowledge, so this is more for learning for me than practical use. Therefore what I really would like to know is how I can get my code to work my way, even if there is a much simpler/quicker/smarter solution.
So what I wanna do is create a string array, and using a loop read in each line from a text file into a corresponding element of the array. That's what I tried to do here, and I would love to hear what solutions you have for this.
{
class Program
{
static void Main(string[] args)
{
StreamReader ki = new StreamReader("kiserlet.txt");
string[] a = new string[15];
Console.ReadLine();
int y = 0;
int n = 0;
for (int i = 0; i > 15; i++)
{
a[n] = Convert.ToString(ki.ReadLine());
n++;
}
for (int x = 0;x > 15;x++)
{
Console.WriteLine(a[y]);
y++;
}
Console.ReadLine();
ki.Close();
}
}
}
You can read each line of the file into an array, then iterate through it.
class Program
{
static void Main(string[] args)
{
// this will read all lines from within the File
// and automatically put them into an array
//
var linesRead = File.ReadLines("kiserlet.txt");
// iterate through each element within the array and
// print it out
//
foreach (var lineRead in linesRead)
{
Console.WriteLine(lineRead);
}
}
}
This question already has answers here:
C# parsing a text file and storing the values in an array
(3 answers)
Closed 5 years ago.
I am trying to store values in an array from reading from a file. I have the reading from a file part but I can't get it to store in an array because it gives me an error "Value cannot be null" because after the loop the value of my variable becomes null and the array cannot be null. Here's what I have. And I realize that the for loop probably isn't in the correct spot so any help with where to put it would be great.
Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
StreamReader myFile = new StreamReader(path);
string input;
int count = 0;
do
{
input = myFile.ReadLine();
if (input != null)
{
WriteLine(input);
count++;
}
} while (input != null);
for (int i = 0; i < count; i++)
{
grades[i] = int.Parse(input);
}
You start the for loop just after exiting from the while loop. And the condition to exit from the while loop is true when input is null. Of course this is not well accepted by Int.Parse.
Instead you can use a single loop, taking in consideration that you don't want to loop more than 50 times otherwise you exceed the array dimensions
int count = 0;
while((input = myFile.ReadLine()) != null && count < 50)
{
WriteLine(input);
grades[count] = int.Parse(input);
count++;
}
However you can have a more flexible way to handle your input if you use a List<int> instead of an array of integers. In this way you don't have to check for the number of lines present in your file
List<int> grades = new List<int>();
while((input = myFile.ReadLine()) != null)
grades.Add(int.Parse(input));
if we want to get really condensed
var grades = File.ReadAllLines(path).Select(l=>Int.Parse(l)).ToArray();
Utilize the Path.Combine() to help you in concatenating paths.
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
String fullPath = Path.Combine(environment, "grades.txt");
int[] grades = File.ReadAllLines(fullPath).Select(p => int.Parse(p)).ToArray<int>();
Console.WriteLine(grades);
Refer to https://www.dotnetperls.com/file-readalllines on how to use File.ReadAllLines() its very handy.
I'm using LINQ here, which sometimes simplifies things. Even though it looks a bit intimidating now. We read all lines, the result of that is then parsed by selecting each one and converting it to an integer then outputting an array of integers and saving that to grades.
Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
using (StreamReader myFile = new StreamReader(path))
{
string input;
int count = 0;
while((!myFile.EndOfStream) && (count < MAX))
{
input = myFile.ReadLine();
if (!String.IsNullOrWhiteSpace(input))
{
WriteLine(input);
grades[count] = int.Parse(input);
count++;
}
}
}
You should definitely use the "using" pattern around your stream object. Got rid of the for-loop for you while maintaining mostly your code and style. Your issue was that you weren't using the input value before moving on to the next line. You only ever had the last value in your original code.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Is someone able to help me out with the following please, I'm trying to split data from an input file (2 pieces of data per line, separated by either of the delimiters specified in the code below). To do this I have declared the string array 'split input', however when I run the program I get a runtime error (screenshot) with the split input line inside the while loop highlighted in yellow. I can't see what I am doing wrong, I'm copying sample code which seems to be working fine :(
NB - the messageBox line below the yellow is just for my testing to prove the split worked
private int DetermineArraySize(StreamReader inputFile)
{
int count = 0;
while (!inputFile.EndOfStream)
{
inputFile.ReadLine();
count++;
}
return count;
}
private void ReadIntoArray(StreamReader inputFile, string[] gameArray, int[] revArray)
{
string rawInput;
string[] splitInput = new string[2];
int count = 0;
char[] delimiters = {'=', '#',};
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
count++;
}
}
}
private void rdGameSalesForm_Load(object sender, EventArgs e)
{
StreamReader inputFile = File.OpenText("GameSales.txt"); //Open Input File
int arraySize = DetermineArraySize(inputFile); //Use input file to determine array size
string[] gameTitle = new string[arraySize]; //Declare array for GameTitle
int[] revenue = new int[arraySize]; ///Declare array for Revenue
ReadIntoArray(inputFile, gameTitle, revenue);
Thanks for your help
Just add check on null.
ReadLine Method returns null if the end of the input stream is reached. It is possible because you check !inputFile.EndOfStream or count < gameArray.Length. So in the second condition has a possibility to get null when input filre reading
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
if(rawInput !=null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
}
}
Check for null instead of end of stream.
while((rawInput = Inputfile.ReadLine()) != null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(...);
}
Developing a small quiz application, thus far I have a text file containing two example questions to see if i can get it working properly before adding more. There are 5 question levels of increasing difficulty, each of these levels contains 10 questions
I'm using a streamreader to read my level 1 questions in from the text file, it reads the first question in fine and the program reads user input and compares it to the answer. If correct the user will move to the next level, but if incorrect I want the program to ask the second question in the file - but it continues to read the first.
I have
static int pos = 0;
serving as my position counter for the reader, but whenever I try to include the position when addressing my struct in the reader like
_question1[pos].q_No = Convert.ToInt32(sreader.ReadLine());
I get an error message:
Cannot apply indexing with [] to an expression of type
'Quiz_Application.Program.question1'
Variables n stuff:
static question1[] _questions1 = new question1[10];
static question2[] _questions2 = new question2[10];
static question3[] _questions3 = new question3[10];
static question4[] _questions4 = new question4[10];
static question5[] _questions5 = new question5[10];
static int score = 0;
static int asked = 0;
static int pos = 0;
static int user_input = 0;
static int user_level = 1;
struct question1
{
public int q_No;
public string Question;
public string Choices;
public int Answer;
}
My reader:
static void QuestionReader_Level1()
{
Console.Clear();
question1 _question1 = new question1();
string filename = #"C:\Users\Craigo\Desktop\Quiz_Application\Files\question1.txt";
while (user_level == 1)
{
using (StreamReader sreader = new StreamReader(filename, true))
{
pos += 1;
asked += 1;
_question1.q_No = Convert.ToInt32(sreader.ReadLine());
Console.WriteLine(_question1.q_No);
_question1.Question = sreader.ReadLine();
Console.WriteLine(_question1.Question);
_question1.Choices = sreader.ReadLine();
Console.WriteLine(_question1.Choices);
_question1.Answer = Convert.ToInt32(sreader.ReadLine());
user_input = Convert.ToInt32(Console.ReadLine());
if (user_input == _question1.Answer)
{
score += 1;
user_level += 1;
Console.WriteLine("\nCongratulations, you have scored 1 point and advanced to level 2");
Console.WriteLine("Score = {0}, Questions Asked = {1}", score, asked);
}
}
}
}
What do I do?
the variable "_question1" is not an array:
question1 _question1 = new question1();
So, when you have "_question1[pos]", it won't work.
Your array is "_questions1" (you are missing the 's'):
question1[] _questions1 = new question1[10];
_questions1[pos] should work
The while loop only loops when the variable user_level is 1. Also , you have added that if the user's input is equal to the answer , user_level will increment by 1 which will equal to 2 and hence , the loop will not run again. However , the fact that the program is still looping means that the condition was not met , which tells us that THE USER INPUT IS NOT EQUAL TO THE ANSWER. Hence , the error might be caused by the file. Would you mind showing the contents of the file?