-2

So this section of code is a small part of my program. It essentially reads through the file of user information which stores full names, bank balances, usernames and passwords.

My question is, why when I enter a username that is NOT in the file, it throws up an error when there is an if statement that says if username is not found, then go to the register method?

    public static int player;
    public static void Username_Check()
    {
        string[] str = File.ReadAllText(@"X:\btec computing\unit 1\C sharp\online_casino_prog\user_info.csv").Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        string[] users = new string[str.Length];
        Console.WriteLine("Enter your username. ");
        string username = Console.ReadLine();
        bool user_found = false;
        for (int i = 0; i < (str.Length); i++)
        {
            string[] person = str[i].Split(',');
            if (person[2] == username)
            {
                Console.WriteLine("Welcome back {0}!", person[0]);
                user_found = true;
                player = i;
                Password_Check();
            }
        }
        if (user_found == false)
        {
            Console.WriteLine("Sorry, we could not find an account linked to the username '{0}', Please register an account with us! ",username);
            Register();
        }
    }

This is the error i am getting:

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at online_casino_prog.Program.Username_Check() in X:\btec computing\unit 1\C sharp\online_casino_prog\online_casino_prog\Program.cs:line 58 at online_casino_prog.Program.Main(String[] args) in X:\btec computing\unit 1\C sharp\online_casino_prog\online_casino_prog\Program.cs:line 30

This snippet shows the csv file I am using to show the user information. It is formatted as such: first name, surname, username, password, balance

  • 1
    Please include the error you get. Your compiler/debugger already did the job of finding out what's wrong, don't let us do that same job again by not telling us what your compiler/debugger found. – nvoigt Mar 13 '19 at 09:42
  • Does your text file have a blank line at the end? or even the last line with a new line? (or any blank lines in the middle) If so `str[str.length-1] == ""` and splitting on that will give you an error on `person[2]`. Add a check for `if (person.length>2)` – freedomn-m Mar 13 '19 at 09:43
  • it might help if you'd add what kind of error you are getting and where exactly. exceptions usually are very informative about what's gone wrong. – Markus Dresch Mar 13 '19 at 09:43
  • @nvoigt i have included the error now, thanks. – Charlie Deville Mar 13 '19 at 09:47
  • now check what's going on in line 27. you are trying to convert a string to a number that is not a valid number. nothing to do with the code you posted. the exception says it all. – Markus Dresch Mar 13 '19 at 09:48
  • @freedomn-m i dont think so, i deleted all info underneath the file, when it writes to it, it adds the line itself. – Charlie Deville Mar 13 '19 at 09:48
  • 1
    Your error and the code you posted do not match. It's probably not in the code you posted. Please provide a [mcve]. Now might be a good point in time to learn how to use a debugger. Get a book or tutorial of your choice and find out why you got this error. – nvoigt Mar 13 '19 at 09:49
  • @MarkusDresch Line 27 has nothng to do with that section, i dont know why that is there. that line is a simple Convert.ToInt32(Console.ReadLine()) – Charlie Deville Mar 13 '19 at 09:50
  • If you split `"1,2,3,"` on `,` then the last entry will be blank. Same with new lines. If your last line ends in a new line then the last `str` will be blank - simple enough to add a check for `if (str == "")` – freedomn-m Mar 13 '19 at 09:50
  • 1
    and that's exactly where the program crashes, because you didn't enter a valid number in Console.ReadLine() – Markus Dresch Mar 13 '19 at 09:50
  • @MarkusDresch the input is either 1 or 2. 1 is login – Charlie Deville Mar 13 '19 at 09:51
  • Can you not step through / run with debugging to see exactly which line it is failing on? – freedomn-m Mar 13 '19 at 09:52
  • store the result of Console.ReadLine in a variable, set a breakpoint after that line and fire up the debugger to check what's really in there. then step along and you'll see where it crashes and why. the exception really says it all. – Markus Dresch Mar 13 '19 at 09:52
  • @freedomn-m i use the school computers and it doenst allow the debug to run. Admin stuff – Charlie Deville Mar 13 '19 at 09:53
  • @MarkusDresch when testing to get the error, i accidentally hit the wrong key. The correct error is now displayed. – Charlie Deville Mar 13 '19 at 09:54
  • 1
    Fair enough re: debugging. The updated error confirms what I said earlier - your input doesn't have 3 comma-separated columns, probably because it's blank. Did you add either of the checks I suggested? – freedomn-m Mar 13 '19 at 09:55
  • You always need to validate inputs, in this case input from a file, regardless of where you get/create your file. – freedomn-m Mar 13 '19 at 09:56
  • what freedomn-m said. `if (person[2] == username)` crashes because person[2] is out of bounds. again, that's exactly what the exception says. imho stackoverflow shouldn't replace a debugger. – Markus Dresch Mar 13 '19 at 09:58
  • @freedomn-m in my for loop, i added a line to confirm that only usernames were being printed and there were no spare lines. So, i took your advice from earlier and used str.length - 1 and it now works. Thanks :D Is this because Str. Length gives the value of 5, and the last username is stored in the 4th row(counting from 0) ? – Charlie Deville Mar 13 '19 at 10:00
  • @MarkusDresch does that mean you cannot compare a blank value to an input? Is that why i had the error? – Charlie Deville Mar 13 '19 at 10:03
  • No. You already had `0 to – freedomn-m Mar 13 '19 at 10:08
  • @freedomn-m Okay, thanks a lot :) – Charlie Deville Mar 13 '19 at 10:14

1 Answers1

0

Your code can be simplified using LINQ

var username = Console.ReadLine();
var lines = File.ReadAllLines("./pathtoyour.csv").Select(line => line.Split(',')); // reads all lines from your csv then each line is transformed into an array of strings
var user = lines.FirstOrDefault(line => line[2] == username); // gets the first occurrence of the username, if no user is found returns null, otherwise user variable will be an array with the row data 

if (user != null)
  Console.WriteLine("Call PasswordCheck()");
else
  Console.WriteLine("Call Register()");
Jorge
  • 57
  • 2
  • 7