-1

What I need to do is to create an array that needs to be filled with the numbers of lines from a text file, so lets say the text file has 5 lines, so the array will be: array [5] I have the following code:

try{ LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("lista de numeros.txt"))); int linenumber = 0; int primero = 0;
            String tmp = new String();
            tmp=lnr.readLine();
                while(tmp != null)
                {
                    linenumber++;  
                    JOptionPane.showMessageDialog (null, (tmp));
                    tmp=lnr.readLine();

                } int mitad=(0+linenumber)/2; int [] array = new int[linenumber];   

What I want to do is to create the array as it is on the last line from the code, I'm trying that way, but if I try to print something like:

JOptionPane.showMessageDialog (null, "Number at half: " + array[mitad]);

Only shows a 0 : Can someone tell me how can I filled the array in the right way please

Tiffany M.
  • 40
  • 1
  • 8
  • You need to add elements (In this case `tmp`) to your `int[] array`. `array[mitad]` is `0` because that is the default value for a variable of type `int`. – MasterBlaster Jun 08 '16 at 22:43

1 Answers1

0

You never fill your int array in your code and default value for int array elements is 0. You could try to use an ArrayList to add your numbers dynamically and then use it to fill the array:

try {
            LineNumberReader lnr = new LineNumberReader(new FileReader(new File("lista de numeros.txt")));
            int linenumber = 0;
            int primero = 0;
            ArrayList<Integer> tmpArrayList = new ArrayList();
            String tmp = new String();
            tmp = lnr.readLine();
            while (tmp != null) {
                tmpArrayList.add(Integer.parseInt(tmp));
                linenumber++;
                JOptionPane.showMessageDialog(null, (tmp));
                tmp = lnr.readLine();

            }
            int mitad = (0 + linenumber) / 2;
            int[] array = new int[linenumber];
            for (int i = 0; i < array.length; i++) {
                array[i] = tmpArrayList.get(i).intValue();
            }

Using ArrayList you don't even need to count linenumbers. Just use tmpArrayList.size() instead whenever you want after your while loop. But notice, your file should have just ints inside, no Strings! Otherwise it won't work.

Alternatively, you could read all the lines again starting a second loop to fill your array. But its not the best way, because in this case you read the file twice: once to count the number of lines to instantiate the array and once to fill it.

Yev
  • 321
  • 2
  • 9