-1

so I'm having trouble with the program recognizing the values of my array elements (The name 'a' does not exist in the current context) , plus i can't get line.split to work(I need it to read the next element after the ',' and it needs to loop for all books (it's a library program). Lastly i can't figure out how to change the "10" (i put the number at random, so it doesn't show me an error) in my for loop, so that the program stops after it read all the info from .txt. Here's the code: EDIT : It doesn't show any more errors, it just crashes now. :(

 using System;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {

        static void Main(string[] args)
        {


            foreach (string line in File.ReadAllLines(@"Duomenys.txt"))
            {
                string[] a = line.Split(',');
                int ISBN = int.Parse(a[0]);
                string BookName = a[1];
                string Author = a[2];
                string Genre = a[3];
                string Publisher = a[4];
                int PublishYear = int.Parse(a[5]);
                int PageNumber = int.Parse(a[6]);
                Console.WriteLine(PublishYear);
                Console.WriteLine();
                Console.ReadKey();

            }
        }

        public void BookWithTheMostPages(int[] a)
        {
            int maxPages = 0;
            string[] lines = File.ReadAllText(@"Duomenys.txt").Split('\n');
            foreach (string line in lines)
            {
                {
                    Console.ReadLine();
                    if (a[6] > maxPages)
                    {
                        maxPages = a[6];

                        Console.WriteLine("Storiausios knygos pavadinimas: {0} , jos autorius(-ė): {1}", a[1], a[2]);
                    }
                }
            }
        }

        public void Publish(string[] a)
        {
            if (!File.Exists(@"Technologija.csv"))
                File.Create(@"Technologija.csv").Dispose();
            using (StreamWriter streamwrite = new StreamWriter(File.OpenWrite(@"Technologija.csv")))
            {
                if (a[2] == "Technologija")
                {
                    streamwrite.WriteLine("\n ISBN : {0}, Pavadinimas: {1}, Autorius: {2}, Tipas: {3}, Leidykla: {4}, Išleidimo Metai: {5}, Puslapių skaičius: {6}", a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
                }
            }
        }

        public void Output(string[] a)
        {
            if (!File.Exists(@"Autoriai.csv"))
                File.Create(@"Autoriai.csv").Dispose();

            using (StreamWriter streamWriter = new StreamWriter(File.OpenWrite(@"Autoriai.csv")))
            {
                streamWriter.WriteLine("\n{0}", a[2]);
            }
        }
        public void Publishyear(string[] a)
        {
            if (a[5] == "2014")
            {
                for (int j = 1; j <= 5; j++)
                    Console.WriteLine("\nKnygos ISBN: {0}, Pavadinimas {1}, Autorius {2}", a[0], a[1], a[2]);
            }
        }
    }
}

Here's the .txt example:

9781408855669, Harry Potter and the Chamber of Secrets, Joanne K Rowling, Apysaka, Bloomsbury Publishing PLC, 1998, 270. (It's one line)

  • Set a breakpoint and debug it to see where the error happens. – Luud van Keulen Sep 27 '16 at 15:05
  • 1
    There are so many mistakes in that code, i don't think it would even compile... – Pikoh Sep 27 '16 at 15:05
  • What's the purpose of the `using` line? It does nothing but open the file and then close and dispose it. Your `foreach` statement also does nothing because of the semi-colon at the end. – Chris Dunaway Sep 27 '16 at 15:20
  • No, it doesn't compile, that's why I'm here, asking for help from people who know things like this, Jesus, so much negativity lol. – JustasRatke Sep 27 '16 at 15:31
  • before you start asking about your code, you should understand the basic of C like language structures. You are missing the `{ }` in `using` and `while`. Start reading this and see the example and you will probably find the issue by yourself: http://stackoverflow.com/questions/75401/uses-of-using-in-c-sharp – Ricardo Pontual Sep 27 '16 at 16:25

3 Answers3

0

a and line are scoped to the static Main method (well, actually a is defined twicein Main, which isn't legal). They do not exist outside of there, unless you make them available, either by passing them in as parameters, or by making them available via fields. You should probably:

  • come up with more meaningful names; a will not help you
  • pass the value in as a parameter (IMO this would be cleaner than fields, but fields would work too)
  • decide whether you are working in instance or static context - at the moment you have both, but never instantiate an object, so you won't be able to call any of the methods

Note that the using and foreach should not be terminated like that ; you probably meant:

foreach (string line in File.ReadAllLines(@"Duomenys.txt"))
{
    string[] a = line.Split(',');
    ...
}

(no need for the using / StreamReader)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Alright so first of all, remove the

using (StreamReader dn = new StreamReader(@"Duomenys.txt"));

if you are not using it. If you are reading the file with File.ReadAllLines you are not going to need it. Also, you are not using your foreach loop correctly. The way you want to go would be something like this:

foreach (string line in File.ReadAllLines(@"Duomenys.txt"))
{
    string[] a = line.split(',');
    int ISBN = Convert.ToInt32(a[0]);
    string BookName = a[1];
    string Author = a[2];
    string Genre = a[3];
    string Publisher = a[4];
    int PublishYear = Convert.ToInt32(a[5]);
    int PageNumber = Convert.ToInt32(a[6]);
}

What I fixed aswell is that you first create a string array named a, but then create a normal string named a which does not work. Also no need to set a size for the array, string.Split() does this automatically.

EDIT: To loop the file lines, assuming they are seperated by line terminators, you could do this:

string[] lines = File.ReadAllText(filename).Split('\n'); 
// '\n' as the regular line terminator
foreach (string line in lines)
{
    // Your other code ...
Ian H.
  • 3,840
  • 4
  • 30
  • 60
  • Thanks to the both of you, I'm a beginner, so all of this is new to me :D. So you guys fixed the line.split error. Now, how do i transfer the parameters exactly? And now for loops with the 10, how do i change it so it stops looping after there's no more info in the txt that it can read? :) – JustasRatke Sep 27 '16 at 15:26
  • Don't know if i did that right yet, but shows no error, so I guess it will work, thanks ! :) – JustasRatke Sep 27 '16 at 16:04
0

'a' only exists in the main function. Like Marc said, you'll want to pass in 'a' as a parameter if you're using it in a different function.

So first line of the function:

public void BookWithTheMostPages() {

}

Should be:

public void BookWithTheMostPages(string[] a)

And should be called in the main function like this:

BookeWithTheMostPages(a);

That-a-ways the function "knows" what 'a' is.

Also, I notice that you're not telling your Main function to run any of the functions you wrote. The program runs everything inside the Main function, not just everything in the Main.cs file. So your 'Publishyear', 'Output', 'Publish', and 'BookWithTheMostPages' function simply aren't running.

Now in regards to your Split function not working here's 2 things:

  1. You have already have something name 'a' in your program, you cannot name another variable by the same name. Make sense?
  2. You must 'Split' into another array, since Split returns a series of strings

So it should look like this:

string[] splitLine = line.split(',');

Also these to lines are not correct:

int PublishYear = Convert.ToInt32(a[5]);
int PageNumber = Convert.ToInt32(a[6]);

If you're wanting to have the 'PublishYear' and 'PageNumber' functions to return an int, they cannot be void functions.

public int Publishyear() {
    /*Write your code in here*/ 
    return year;
}

Then later you can use the Function like this to get a value.

int i = Publishyear();

Same goes for your 'PageNumber' Function.

There are still a lot of little errors in the program I haven't mentioned and it would take forever to write down everyone with an explination, but for a beginner like yourself take it piece by piece. Follow a guideline like this:

  1. Write down what the program is supposed to do on paper.
  2. Write a small portion of code (couple lines)
  3. Test it.
  4. Repeat steps 2 and 3 until finished.

One last thing, get in the habit of naming your variables with more descriptive names. 'a' doesn't let a reader know at a glance what 'a' is. Write code that is easy for other people to read. I know at the beginning programming can seems very hard and confusing, but keep at it, don't give up. And little by little you'll get this whole programming things figured out.

Cheers!

Wyatt Shuler
  • 334
  • 2
  • 12
  • Thanks so much, it solved most of my problems, now the program crashes, and i don't really know why lol. – JustasRatke Sep 27 '16 at 16:24
  • I don't know if you've encountered breakpoints, but take a look at this article: [link](https://msdn.microsoft.com/en-us/library/5557y8b4.aspx). You can go through the program line by line and see how the program works. Good luck fella! – Wyatt Shuler Sep 27 '16 at 16:57
  • The problem seems to be the ISBN, it crashes when it tries to read it. :( – JustasRatke Sep 27 '16 at 17:07