Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Read A File and Store Values into a 2-Dimensional Integer Array?

  1. #1
    Junior Member
    Join Date
    Jun 2010
    Posts
    28
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default (SOLVED) Read A File and Store Values into a 2-Dimensional Integer Array?

    Hello! On top of the other program I have is one that deals with taking values from a file, "input.txt" (click on the file name), storing those values into a 2D array, and printing them out like so:

    6 5 4 1
    2 3 4 5
    8 10 12 23
    43 84 11 4

    I also need to calculate the sum of the diagonal from the top left of the array to the bottom right of the array. In this case, the sum would be 25 (6+3+12+4).

    And in addition to that, I need to make a transpose of that output and again calculate the sum of the diagonal from the top left of the array to the bottom right of the array like this:

    6 2 8 43
    5 3 10 84
    4 4 12 11
    1 5 23 4
    Sum = 25

    This is my code so far:

    import java.io.*;
    import java.util.*;
     
    class Doubles
    {
      public static void main (String []args)
      {
        try
        {
          int i, j, n = 4;
          int[][] array = new int[n][n];
          String line;
     
          FileInputStream fstream  = new FileInputStream("input.txt");
          Scanner scan = new Scanner(fstream);
          DataInputStream In = new DataInputStream(fstream);
          BufferedReader reader = new BufferedReader(new InputStreamReader(In));
     
          //Stores data into an array
          while ((line = reader.readLine()) != null)
          {
            array[0][0] = line;
          }
          reader.close();
          System.out.println("Here is the matrix version: ");
     
          for (i=0; i<n; i++)
          {
            for (j = 0; j<n; j++)
            { 
              System.out.print(array[i][j]);
            }
          }
        }
        catch (Throwable e)
        {
          System.out.println("This is not valid!"); 
        }  
      }
    }

    Obviously the code isn't done yet, but as you can tell I have no idea how to store the values into the 2D array, let alone calculate the sum and print that out. Any advice? Thanks in advance!
    Last edited by Kimimaru; February 13th, 2011 at 04:36 PM.


  2. #2
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Read A File and Store Values into a 2-Dimensional Integer Array?

    Here's what you need to know.
    1) Read a file (DONE)
    2) Tokenize a String (DONE)
    3) Convert a string to an int
    To convert a String to an Int use the following code:
    Integer.parseInt(inputString);

    Now I'm going to show you the algorithm in pseudo-code that way you can still learn.
    public class test {
        public static void main(String[] args)
        {
            int[][] data = new Integer[4][4]();
            makeInputStream;
            int row, column = 0;
            while(inputstream has more lines)
            {
                 tokenize the current line to remove all spaces;
                 while (tokenizer has more tokens)
                 {
                     Integer.parseInt(token);
                     column++
                 }
                row++;
            }
     
            //Now that we stored the file into a 4x4 array we need to add the diagonals 
     
           int x, y, total;
     
           while (x is less than data's columns and Y is less than datas rows)
           {
                total += data[x][y]
                x++;
                y++;
           }
     
           System.out.println(total);
        }
    }

  3. The Following User Says Thank You to Brt93yoda For This Useful Post:

    Kimimaru (February 9th, 2011)

  4. #3
    Junior Member
    Join Date
    Jun 2010
    Posts
    28
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Read A File and Store Values into a 2-Dimensional Integer Array?

    Why would I need to remove all the spaces? I need to have a space after each number.

    Also, when did I tokenize a string? My professor told us we had to use the InputStream, but he barely explained how it works. Since that's the case I also don't know how to check if the input stream has more lines.

  5. #4
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Read A File and Store Values into a 2-Dimensional Integer Array?

    You do need to remove all of the spaces after you read the file. You can't convert the string "10 " to the int 10.

    Also, when did I tokenize a string? My professor told us we had to use the InputStream, but he barely explained how it works. Since that's the case I also don't know how to check if the input stream has more lines.
    You checked if the stream had more lines in your OP.

    while ((line = reader.readLine()) != null) //Remember?

    You were also using Stringtokenizers in your last thread, so I assumed you know how to use them.

  6. The Following User Says Thank You to Brt93yoda For This Useful Post:

    Kimimaru (February 9th, 2011)

  7. #5
    Junior Member
    Join Date
    Jun 2010
    Posts
    28
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Read A File and Store Values into a 2-Dimensional Integer Array?

     //Stores data into an array
          while ((line = reader.readLine()) != null)
          {
            StringTokenizer line2 = new StringTokenizer(line);
     
            while (line2.hasMoreTokens())
            {
              array[column][row] = Integer.parseInt(line2.nextToken());
              column++;
            }
            row++;
          }

    for (i=0; i<column; i++)
          {
            for (j=0; j<row; j++)
            {
              sum += array[i][j];
            }
          }
          System.out.println("The sum is: " + sum);
        }

    When I try this the exception kicks in and states that it's not valid. I know it has to do with the fact that I'm going further than the array's limits, but what can I do then? "column" will keep incrementing past the array's limits in the first while loop.

    Also, it doesn't print out how I want it to print out. How I want it to print out can be found in my original post.
    Last edited by Kimimaru; February 10th, 2011 at 01:48 AM.

  8. #6
    Junior Member
    Join Date
    Jun 2010
    Posts
    28
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Read A File and Store Values into a 2-Dimensional Integer Array?

    Sorry for double posting, but I just want to say that this particular assignment is due Friday and I'd like to get it done as soon as I can, considering all the other work I have to get done this week.

Similar Threads

  1. Two-Dimensional Array and Loops
    By astrojunk in forum Java Theory & Questions
    Replies: 2
    Last Post: February 11th, 2011, 07:18 AM
  2. Store Values in 2D array and output to textarea
    By raverz1tildawn in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 7th, 2011, 03:13 PM
  3. how to read an integer of DOUBLE datatype with type casting
    By amr in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 14th, 2010, 03:03 PM
  4. How to write 2 dimensional array of float numbers to binary file?
    By Ghuynh in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: June 17th, 2010, 04:26 PM
  5. 2 dimensional array alternative ???
    By zeeshanmirza in forum Java SE APIs
    Replies: 1
    Last Post: February 23rd, 2010, 06:18 PM