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 16 of 16

Thread: text file array help

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default read file into matrix

    Hello All,

    I am stuck on my assignment and It is due tonight @ midnight. I am so stressed about it, and need some help, I really tried all I can do with it, and need some assistance.


    Assignment: Develop a GUI-based program to read the entries of a matrix from a text file. The first number is the number of rows; the second number is the number of columns. The remaining numbers are integers between 1 and 9 in row by row order. Scan the matrix, highlight (display the entries in different color) all cells that form a group of five cells with the same value horizontally, vertically or diagonally.

    Example of text(.txt) file:
    7 7
    3 6 2 3 1 6 1
    3 6 6 6 6 6 9
    3 9 3 6 2 9 3
    3 5 9 4 9 5 5
    3 2 8 9 8 6 7
    2 4 9 3 9 9 8
    1 3 9 9 9 9 8

    Example of output:
    3 6 2 3 1 6 1
    3 6 6 6 6 6 9
    3 9 3 6 2 9 3
    3 5 9 4 9 5 5
    3 2 8 9 8 6 7
    2 4 9 3 9 9 8
    1 3 9 9 9 9 8


    * ^^this would be what it would look like when displayed in the GUI. But it would be colored. Anything that has 5 in a row ...
    My Class File:
    // GUI-related imports
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Scanner;
     
    // File-related imports
     
    import java.io.FileReader;   // both needed
    import java.io.BufferedReader;  // for line input
     
    import java.io.IOException;
     
     
    public class FiveInARow
    {
     
     byte[][] tag = new byte[100][100];
     int[][] matrix = new int[100][100];
     int row;
     int col;
     String filePath, fileName;
     
     // Constructor
     public FiveInARow()
     {
      row = 0;
      col = 0;
     }
     
     public void ReadFile()
     {
      // Initialize TAG(s) to 0
      for(int i =0; i< tag.length; i++)
        for(int j =0; i< tag.length; j++)
           tag[i][j] = 0;
     
      //Place open dialogue here
      String filePath = null;
      String fileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 filePath = chooser.getSelectedFile().getPath();
                 fileName = chooser.getSelectedFile().getName();
               }
     
     
      // Define & Instantiate File
      Scanner inputStream = new Scanner(filePath);
      row  = inputStream.nextInt();
      col  = inputStream.nextInt();
     
      for(int i =0; i< row; i++)    // rows
      {
       for(int j = 0; j < col; j++)   //columns
       {
         matrix[i][j] = inputStream.nextInt();
       }
      }
     
     } // End of ReadFile method
     
     public void Process()
     {
     
      // Go through the matrix
      for(int i = 0; i < row; i++)
      {
        for(int j = 0; j < col; j++)
        {
          // Checking the matrix horizantally
          if(j <= col-5)  // Checks the boundaries of horizantal elements
     
            if (matrix[i][j] == matrix[i][j+1]
                &&(matrix[i][j+1] == matrix[i][j+2])
                &&(matrix[i][j+2] == matrix[i][j+3])
                &&(matrix[i][j+3] == matrix[i][j+4]))
     
            tag[i][j] = 1;
     
            // Checking the matrix vertically
           if(i <= row-5)  // Checks the boundaries of vertical elements
     
            if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 2;
     
           // Checking the matrix's right diagnol CHANGEEEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 3;
     
           // Checking the matrix's left diagnol   CHANGEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 4;
        }
      }
     
     
     } // End of Process method
     
     
     //Setting colors to tags
     if (tag[i][j] = 0)
       g.setColor(black);
     else
       if (tag[i][j] = 1)
       g.setColor(blue);
     else
       if (tag = 2)
       g.setColor(red);
     else
       if (tag = 3)
       g.setColor(green);
     else
       if (tag = 4)
       g.setColor(purple);
     
     
    }



    My DRIVER Class:
    // GUI-related imports
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Scanner;
     
    // File-related imports
    import java.io.FileReader;   // both needed
    import java.io.IOException;
     
    public class  Project3Main extends Frame implements ActionListener
    {
     // File Parameters
     FiveInARow f = new FiveInARow();
     String dataFilePath = null;
     String dataFileName = null;
     int[][] Data = new int[100][100];
     int[][] Tag = new int [100][100];
     int row = 0;
     int column = 0;
     
     // Retrieved command code
     String command = "";
     
     public static void main(String[] args)
     {
      Frame frame = new  Project3Main();
     
      frame.setResizable(true);
      frame.setSize(1000,700);
      frame.setVisible(true);
     
     }
     
     public  Project3Main()
     {
      setTitle("2D Arrays");
     
      // Create Menu Bar
      MenuBar mb = new MenuBar();
      setMenuBar(mb);
     
      // Create Menu Group Labeled "File"
      Menu fileMenu = new Menu("File");
     
      // Add it to Menu Bar
      mb.add(fileMenu);
     
      // Create Menu Items
      // Add action Listener 
      // Add to "File" Menu Group
       MenuItem miReadData = new MenuItem("Read Data");
       miReadData.addActionListener(this);
       fileMenu.add(miReadData);
     
       MenuItem miProcess = new MenuItem("Process");
       miProcess.addActionListener(this);
       fileMenu.add(miProcess);
     
       MenuItem miExit = new MenuItem("Exit");
       miExit.addActionListener(this);
       fileMenu.add(miExit);
     
      // End program when window is closed
      WindowListener l = new WindowAdapter()
      {
     
       public void windowClosing(WindowEvent ev)
       {
        System.exit(0);
       }
     
       public void windowActivated(WindowEvent ev)
       {
        repaint();
       }
     
       public void windowStateChanged(WindowEvent ev)
       {
        repaint();
       }
     
      };
     
      ComponentListener k = new ComponentAdapter()
      {
       public void componentResized(ComponentEvent e) 
       {
              repaint();           
          }
      };
     
      // register listeners
      this.addWindowListener(l);
      this.addComponentListener(k);
     
     }
     
    //******************************************************************************
    //  called by windows manager whenever the application window performs an action
    //  (select a menu item, close, resize, ....
    //******************************************************************************
     
     public void actionPerformed (ActionEvent ev)
      {
       // figure out which command was issued  
       command = ev.getActionCommand();
     
       // take action accordingly 
       if("Read Data".equals(command))
       {
     
    ///////////////////////////////////////////////////////////////// call readfile method in your class to do this
     
     
                                    dataFilePath = null;
        dataFileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 dataFilePath = chooser.getSelectedFile().getPath();
                 dataFileName = chooser.getSelectedFile().getName();
               }
             try 
         {   
     
     
               /*
           * Scan the file and place it's contents into an array of Integers.
           */
           Scanner inputStream  = new Scanner(new FileReader(dataFilePath));
           int intLine;
           row = inputStream.nextInt();
           column = inputStream.nextInt();
            for (int i=0; i < row; i++){
            for (int j = 0 ; j < column; j++)
            {
     
             intLine = inputStream.nextInt();
     
     
                   } 
         }
         }
     
         catch(IOException ioe)
         {
          System.exit(0);
         }
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        repaint();
       }
       else
        if("Process".equals(command))
        {
         // call process method in your class 
         f.Process();
         // determine if cells form a 5-cell same-valued block, mark them true in Tags array
     
     
     
         repaint();
        }
       else
        if("Exit".equals(command))
        {
         System.exit(0);
        }
     
      }
    //********************************************************
    // called by repaint() to redraw the screen
    //********************************************************
     
      public void paint(Graphics g)
      {
     
       int ww = (int)this.getWidth();
       int wh = (int)this.getHeight() -40;
     
       if("Read Data".equals(command))
       {
        // Acknowledge that file was opened
        if (dataFileName != null)
        {
         g.drawString("File --  "+dataFileName+"  -- was successfully opened", ww/2-150, wh/2);
        }
        else
        {
         g.drawString("NO File is Open", 400, 400);
        }
     
        return; 
       }
       else
       if("Process".equals(command))
       {
     
     
        // Display the results
        int x = (ww-column*20)/2;
        int y = (wh-row*20)/2;
     
        for (int i=0; i<row; i++)
        {
         for (int j=0; j<column; j++)
         {
          g.setColor(Color.BLACK);
          if (Tag[i][j] == 1)
           g.setColor(Color.RED);
          //******* set color for the other directions
     
          g.drawString( ((Integer)Data[i][j]).toString(), x, y);
          x=x+20;
         }
        x = (ww-column*20)/2;
        y=y+20;
        }
        return; 
       }
     
      }
     
    }




    EX.
    • 0=black(when there is no combo. of 5)
    • 1=blue(horizantal combo of 5)
    • 2=red(vertical combo of 5)
    • 3=green(right diagnol combo of 5)
    • 4=purple(left diagol combo of 5)
    Attached Files Attached Files
    Last edited by omgitztmarie; March 9th, 2014 at 06:51 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    Duplicate posts merged.

    Do you have a specific question about the assignment and the problems you are having.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: text file array help

    Quote Originally Posted by Norm View Post
    Duplicate posts merged.

    Do you have a specific question about the assignment and the problems you are having.

    YES, I do.
    1)My Process method isnt working and displaying the .txt file I opened.
    2) I dont know how to correctly create the "tags" my teacher specifies to make each # tag represent a color.
    3) I need help counging the array in 5's (in a row) to display them each in a color....ex. 5 of the same # horizantal = blue, 5 vertical in a row = red...5 right diagnal in a row = green, 5 left diagnol = purple.

    PLEASE HELP ME. Im desprate. I do not want a 0 for a grade.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    )My Process method isnt working and displaying the .txt file I opened.
    What does "isn't working" mean? How is the txt file supposed to be displayed?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: text file array help

    Quote Originally Posted by Norm View Post
    What does "isn't working" mean? How is the txt file supposed to be displayed?
    Ok NORM, for example when I click "Read Data" in my menu, it opens my file usccessfully. However when I click "Process" in the menu, I get an array of 0's back in return. When I am supposed to get my SAME ARRAY BACK, color coded with the tags.

    when tag = 0 (black)...tag= 1(blue), tag=2(red), tag=3(green), tag =4(purple)

    This is totally stressing me out and I dont know how to finish this ,and get it work. =(

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    The posted code does not compile without errors.
    Please fix the errors and post new code
    or post the error messages you are having problems with.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: text file array help

    Here is the edited code. I deleted the tag color assignments at the end. So this can work.
    CLASS:
    // GUI-related imports
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Scanner;
     
    // File-related imports
     
    import java.io.FileReader;   // both needed
    import java.io.BufferedReader;  // for line input
     
    import java.io.IOException;
     
     
    public class FiveInARow
    {
     
     byte[][] tag = new byte[100][100];
     int[][] matrix = new int[100][100];
     int row;
     int col;
     String filePath, fileName;
     
     // Constructor
     public FiveInARow()
     {
      row = 0;
      col = 0;
     }
     
     public void ReadFile()
     {
      // Initialize TAG(s) to 0
      for(int i =0; i< tag.length; i++)
        for(int j =0; i< tag.length; j++)
           tag[i][j] = 0;
     
      //Place open dialogue here
      String filePath = null;
      String fileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 filePath = chooser.getSelectedFile().getPath();
                 fileName = chooser.getSelectedFile().getName();
               }
     
     
      // Define & Instantiate File
      Scanner inputStream = new Scanner(filePath);
      row  = inputStream.nextInt();
      col  = inputStream.nextInt();
     
      for(int i =0; i< row; i++)    // rows
      {
       for(int j = 0; j < col; j++)   //columns
       {
         matrix[i][j] = inputStream.nextInt();
       }
      }
     
     } // End of ReadFile method
     
     public void Process()
     {
     
      // Go through the matrix
      for(int i = 0; i < row; i++)
      {
        for(int j = 0; j < col; j++)
        {
          // Checking the matrix horizantally
          if(j <= col-5)  // Checks the boundaries of horizantal elements
     
            if (matrix[i][j] == matrix[i][j+1]
                &&(matrix[i][j+1] == matrix[i][j+2])
                &&(matrix[i][j+2] == matrix[i][j+3])
                &&(matrix[i][j+3] == matrix[i][j+4]))
     
            tag[i][j] = 1;
     
            // Checking the matrix vertically
           if(i <= row-5)  // Checks the boundaries of vertical elements
     
            if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 2;
     
           // Checking the matrix's right diagnol CHANGEEEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 3;
     
           // Checking the matrix's left diagnol   CHANGEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 4;
        }
      }
     
     
     } // End of Process method
     
     
     
     
     
    }

    DRIVER CLASS:
    // GUI-related imports
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Scanner;
     
    // File-related imports
    import java.io.FileReader;   // both needed
    import java.io.IOException;
     
    public class  Project3Main extends Frame implements ActionListener
    {
     // File Parameters
     FiveInARow f = new FiveInARow();
     String dataFilePath = null;
     String dataFileName = null;
     int[][] Data = new int[100][100];
     int[][] Tag = new int [100][100];
     int row = 0;
     int column = 0;
     
     // Retrieved command code
     String command = "";
     
     public static void main(String[] args)
     {
      Frame frame = new  Project3Main();
     
      frame.setResizable(true);
      frame.setSize(1000,700);
      frame.setVisible(true);
     
     }
     
     public  Project3Main()
     {
      setTitle("2D Arrays");
     
      // Create Menu Bar
      MenuBar mb = new MenuBar();
      setMenuBar(mb);
     
      // Create Menu Group Labeled "File"
      Menu fileMenu = new Menu("File");
     
      // Add it to Menu Bar
      mb.add(fileMenu);
     
      // Create Menu Items
      // Add action Listener 
      // Add to "File" Menu Group
       MenuItem miReadData = new MenuItem("Read Data");
       miReadData.addActionListener(this);
       fileMenu.add(miReadData);
     
       MenuItem miProcess = new MenuItem("Process");
       miProcess.addActionListener(this);
       fileMenu.add(miProcess);
     
       MenuItem miExit = new MenuItem("Exit");
       miExit.addActionListener(this);
       fileMenu.add(miExit);
     
      // End program when window is closed
      WindowListener l = new WindowAdapter()
      {
     
       public void windowClosing(WindowEvent ev)
       {
        System.exit(0);
       }
     
       public void windowActivated(WindowEvent ev)
       {
        repaint();
       }
     
       public void windowStateChanged(WindowEvent ev)
       {
        repaint();
       }
     
      };
     
      ComponentListener k = new ComponentAdapter()
      {
       public void componentResized(ComponentEvent e) 
       {
              repaint();           
          }
      };
     
      // register listeners
      this.addWindowListener(l);
      this.addComponentListener(k);
     
     }
     
    //******************************************************************************
    //  called by windows manager whenever the application window performs an action
    //  (select a menu item, close, resize, ....
    //******************************************************************************
     
     public void actionPerformed (ActionEvent ev)
      {
       // figure out which command was issued  
       command = ev.getActionCommand();
     
       // take action accordingly 
       if("Read Data".equals(command))
       {
     
    ///////////////////////////////////////////////////////////////// call readfile method in your class to do this
     
     
                                    dataFilePath = null;
        dataFileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 dataFilePath = chooser.getSelectedFile().getPath();
                 dataFileName = chooser.getSelectedFile().getName();
               }
             try 
         {   
     
     
               /*
           * Scan the file and place it's contents into an array of Integers.
           */
           Scanner inputStream  = new Scanner(new FileReader(dataFilePath));
           int intLine;
           row = inputStream.nextInt();
           column = inputStream.nextInt();
            for (int i=0; i < row; i++){
            for (int j = 0 ; j < column; j++)
            {
     
             intLine = inputStream.nextInt();
     
     
                   } 
         }
         }
     
         catch(IOException ioe)
         {
          System.exit(0);
         }
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        repaint();
       }
       else
        if("Process".equals(command))
        {
         // call process method in your class 
         f.Process();
         // determine if cells form a 5-cell same-valued block, mark them true in Tags array
     
     
     
         repaint();
        }
       else
        if("Exit".equals(command))
        {
         System.exit(0);
        }
     
      }
    //********************************************************
    // called by repaint() to redraw the screen
    //********************************************************
     
      public void paint(Graphics g)
      {
     
       int ww = (int)this.getWidth();
       int wh = (int)this.getHeight() -40;
     
       if("Read Data".equals(command))
       {
        // Acknowledge that file was opened
        if (dataFileName != null)
        {
         g.drawString("File --  "+dataFileName+"  -- was successfully opened", ww/2-150, wh/2);
        }
        else
        {
         g.drawString("NO File is Open", 400, 400);
        }
     
        return; 
       }
       else
       if("Process".equals(command))
       {
     
     
        // Display the results
        int x = (ww-column*20)/2;
        int y = (wh-row*20)/2;
     
        for (int i=0; i<row; i++)
        {
         for (int j=0; j<column; j++)
         {
          g.setColor(Color.BLACK);
          if (Tag[i][j] == 1)
           g.setColor(Color.RED);
          //******* set color for the other directions
     
          g.drawString( ((Integer)Data[i][j]).toString(), x, y);
          x=x+20;
         }
        x = (ww-column*20)/2;
        y=y+20;
        }
        return; 
       }
     
      }
     
    }

    **I just deleted the tags at the end with the colors. That is what made the compilation errors, however I still have problems with the Process method above.

    **Next is how to Number coordinate the tags w/ the colors I need. Because the way I tried it did not work apparently.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    Have you tested the code that reads in the file to see that the numbers are getting into the 2D array?
    The Arrays class's deepToString() method will format a 2D array for printing:
    System.out.println("an ID "+ java.util.Arrays.deepToString(theArrayNameHere));
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default 2D Array - Read from .txt HELP!

    Hello All,

    I am stuck on my assignment and It is due very soon.


    Assignment: Develop a GUI-based program to read the entries of a matrix from a text file. The first number is the number of rows; the second number is the number of columns. The remaining numbers are integers between 1 and 9 in row by row order. Scan the matrix, highlight (display the entries in different color) all cells that form a group of five cells with the same value horizontally, vertically or diagonally.

    Example of text(.txt) file:
    7 7
    3 6 2 3 1 6 1
    3 6 6 6 6 6 9
    3 9 3 6 2 9 3
    3 5 9 4 9 5 5
    3 2 8 9 8 6 7
    2 4 9 3 9 9 8
    1 3 9 9 9 9 8

    Example of output:
    3 6 2 3 1 6 1
    3 6 6 6 6 6 9
    3 9 3 6 2 9 3
    3 5 9 4 9 5 5
    3 2 8 9 8 6 7
    2 4 9 3 9 9 8
    1 3 9 9 9 9 8


    * ^^this would be what it would look like when displayed in the GUI. But it would be colored. Anything that has 5 in a row ...


    Class File:
    // GUI-related imports
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Scanner;
     
    // File-related imports
     
    import java.io.FileReader;   // both needed
    import java.io.BufferedReader;  // for line input
     
    import java.io.IOException;
     
     
    public class FiveInARow
    {
     
     byte[][] tag = new byte[100][100];
     int[][] matrix = new int[100][100];
     int row;
     int col;
     String filePath, fileName;
     
     // Constructor
     public FiveInARow()
     {
      row = 0;
      col = 0;
     }
     
     public void ReadFile()
     {
      // Initialize TAG(s) to 0
      for(int i =0; i< tag.length; i++)
        for(int j =0; i< tag.length; j++)
           tag[i][j] = 0;
     
      //Place open dialogue here
      String filePath = null;
      String fileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 filePath = chooser.getSelectedFile().getPath();
                 fileName = chooser.getSelectedFile().getName();
               }
     
     
      // Define & Instantiate File
      Scanner inputStream = new Scanner(filePath);
      row  = inputStream.nextInt();
      col  = inputStream.nextInt();
     
      for(int i =0; i< row; i++)    // rows
      {
       for(int j = 0; j < col; j++)   //columns
       {
         matrix[i][j] = inputStream.nextInt();
       }
      }
     
     } // End of ReadFile method
     
     public void Process()
     {
     
      // Go through the matrix
      for(int i = 0; i < row; i++)
      {
        for(int j = 0; j < col; j++)
        {
          // Checking the matrix horizantally
          if(j <= col-5)  // Checks the boundaries of horizantal elements
     
            if (matrix[i][j] == matrix[i][j+1]
                &&(matrix[i][j+1] == matrix[i][j+2])
                &&(matrix[i][j+2] == matrix[i][j+3])
                &&(matrix[i][j+3] == matrix[i][j+4]))
     
            tag[i][j] = 1;
     
            // Checking the matrix vertically
           if(i <= row-5)  // Checks the boundaries of vertical elements
     
            if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 2;
     
           // Checking the matrix's right diagnol CHANGEEEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 3;
     
           // Checking the matrix's left diagnol   CHANGEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 4;
        }
      }
     
     
     } // End of Process method
     
     
     
     
     
    }





    Driver:
    // GUI-related imports
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Scanner;
     
    // File-related imports
    import java.io.FileReader;   // both needed
    import java.io.IOException;
     
    public class  Project3Main extends Frame implements ActionListener
    {
     // File Parameters
     FiveInARow f = new FiveInARow();
     String dataFilePath = null;
     String dataFileName = null;
     int[][] Data = new int[100][100];
     int[][] Tag = new int [100][100];
     int row = 0;
     int column = 0;
     
     // Retrieved command code
     String command = "";
     
     public static void main(String[] args)
     {
      Frame frame = new  Project3Main();
     
      frame.setResizable(true);
      frame.setSize(1000,700);
      frame.setVisible(true);
     
     }
     
     public  Project3Main()
     {
      setTitle("2D Arrays");
     
      // Create Menu Bar
      MenuBar mb = new MenuBar();
      setMenuBar(mb);
     
      // Create Menu Group Labeled "File"
      Menu fileMenu = new Menu("File");
     
      // Add it to Menu Bar
      mb.add(fileMenu);
     
      // Create Menu Items
      // Add action Listener 
      // Add to "File" Menu Group
       MenuItem miReadData = new MenuItem("Read Data");
       miReadData.addActionListener(this);
       fileMenu.add(miReadData);
     
       MenuItem miProcess = new MenuItem("Process");
       miProcess.addActionListener(this);
       fileMenu.add(miProcess);
     
       MenuItem miExit = new MenuItem("Exit");
       miExit.addActionListener(this);
       fileMenu.add(miExit);
     
      // End program when window is closed
      WindowListener l = new WindowAdapter()
      {
     
       public void windowClosing(WindowEvent ev)
       {
        System.exit(0);
       }
     
       public void windowActivated(WindowEvent ev)
       {
        repaint();
       }
     
       public void windowStateChanged(WindowEvent ev)
       {
        repaint();
       }
     
      };
     
      ComponentListener k = new ComponentAdapter()
      {
       public void componentResized(ComponentEvent e) 
       {
              repaint();           
          }
      };
     
      // register listeners
      this.addWindowListener(l);
      this.addComponentListener(k);
     
     }
     
    //******************************************************************************
    //  called by windows manager whenever the application window performs an action
    //  (select a menu item, close, resize, ....
    //******************************************************************************
     
     public void actionPerformed (ActionEvent ev)
      {
       // figure out which command was issued  
       command = ev.getActionCommand();
     
       // take action accordingly 
       if("Read Data".equals(command))
       {
     
    ///////////////////////////////////////////////////////////////// call readfile method in your class to do this
     
     
                                    dataFilePath = null;
        dataFileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 dataFilePath = chooser.getSelectedFile().getPath();
                 dataFileName = chooser.getSelectedFile().getName();
               }
             try 
         {   
     
     
               /*
           * Scan the file and place it's contents into an array of Integers.
           */
           Scanner inputStream  = new Scanner(new FileReader(dataFilePath));
           int intLine;
           row = inputStream.nextInt();
           column = inputStream.nextInt();
            for (int i=0; i < row; i++){
            for (int j = 0 ; j < column; j++)
            {
     
             intLine = inputStream.nextInt();
     
     
                   } 
         }
         }
     
         catch(IOException ioe)
         {
          System.exit(0);
         }
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        repaint();
       }
       else
        if("Process".equals(command))
        {
         // call process method in your class 
         f.Process();
         // determine if cells form a 5-cell same-valued block, mark them true in Tags array
     
     
     
         repaint();
        }
       else
        if("Exit".equals(command))
        {
         System.exit(0);
        }
     
      }
    //********************************************************
    // called by repaint() to redraw the screen
    //********************************************************
     
      public void paint(Graphics g)
      {
     
       int ww = (int)this.getWidth();
       int wh = (int)this.getHeight() -40;
     
       if("Read Data".equals(command))
       {
        // Acknowledge that file was opened
        if (dataFileName != null)
        {
         g.drawString("File --  "+dataFileName+"  -- was successfully opened", ww/2-150, wh/2);
        }
        else
        {
         g.drawString("NO File is Open", 400, 400);
        }
     
        return; 
       }
       else
       if("Process".equals(command))
       {
     
     
        // Display the results
        int x = (ww-column*20)/2;
        int y = (wh-row*20)/2;
     
        for (int i=0; i<row; i++)
        {
         for (int j=0; j<column; j++)
         {
          g.setColor(Color.BLACK);
          if (Tag[i][j] == 1)
           g.setColor(Color.RED);
          //******* set color for the other directions
     
          g.drawString( ((Integer)Data[i][j]).toString(), x, y);
          x=x+20;
         }
        x = (ww-column*20)/2;
        y=y+20;
        }
        return; 
       }
     
      }
     
    }


    EX.
    0=black(when there is no combo. of 5)
    1=blue(horizantal combo of 5)
    2=red(vertical combo of 5)
    3=green(right diagnol combo of 5)
    4=purple(left diagol combo of 5)


    MY QUESTION:
    I think there is a problem with the code that reads in the file to see that the numbers are getting into the 2D array because when I click "Read Data" in my menu, it opens my file usccessfully. However when I click "Process" in the menu, I get an array of 0's back in return. When I am supposed to get my SAME ARRAY BACK, color coded with the tags.

    when tag = 0 (black)...tag= 1(blue), tag=2(red), tag=3(green), tag =4(purple)

    This is totally stressing me out and I dont know how to finish this ,and get it work.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    Posts merged.
    Did you do what I suggested in post#8?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: text file array help

    Quote Originally Posted by Norm View Post
    Posts merged.
    Did you do what I suggested in post#8?
    I am supposed to use the readFile method. Not deepToString. Ive been stuck on this for days now. Ive been all over the internet & back trying to figure this out. And once again, I am back here hoping for some legit help.

    My program is based off of what the teacher gave me. I am going off her code. I didnt start this from scratch, she did. Therefore all of this confuses me being that I did not make it myself.

    She posts comments in the code as to where things should go. I thought I did it correct, but apparently did not. I AM NEW AT THIS. I DONT KNOW WHAT I AM DOING AT ALL.

    But I know the problem must be the problem must be in the ReadData method...or Process method...because I am STILL getting the SAME matrix of 0's back when I press Process in my menu.

    --- Update ---

    Sorry for the duplicate posts. Im new to this site, and cant seem to find you DELETE button.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    To get this code to work, you need to spend some time figuring out what it does so you can modify it to do what you want it to do.
    One question is: Does the existing code read the data in the file and store it correctly in the array?
    To see if that part of the code is working, print out the contents of the array where the data is stored after it was read. An easy way to print out the contents of a 2D array is the method I suggested in post#8
    System.out.println("an ID "+ java.util.Arrays.deepToString(theArrayNameHere));

    Check what is printed against what is in the file to be sure it has been read and stored OK.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: text file array help

    Quote Originally Posted by Norm View Post
    To get this code to work, you need to spend some time figuring out what it does so you can modify it to do what you want it to do.
    One question is: Does the existing code read the data in the file and store it correctly in the array?
    To see if that part of the code is working, print out the contents of the array where the data is stored after it was read. An easy way to print out the contents of a 2D array is the method I suggested in post#8
    System.out.println("an ID "+ java.util.Arrays.deepToString(theArrayNameHere));

    Check what is printed against what is in the file to be sure it has been read and stored OK.
    Thanks for responding. Where would I put this in my code?
    System.out.println("an ID "+ java.util.Arrays.deepToString(theArrayNameHere));

    --- Update ---

    Ok well I tried this in my ReadFile methof of my FiveInARow.java class. This is the only thing I changed. I got back the same 0's as before.

    public void ReadFile()
     {
      // Initialize TAG(s) to 0
      for(int i =0; i< tag.length; i++)
        for(int j =0; i< tag.length; j++)
           tag[i][j] = 0;
     
      //Place open dialogue here
      String filePath = null;
      String fileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 filePath = chooser.getSelectedFile().getPath();
                 fileName = chooser.getSelectedFile().getName();
               }
     
     
      // Define & Instantiate File
      Scanner inputStream = new Scanner(filePath);
      row  = inputStream.nextInt();
      col  = inputStream.nextInt();
     
      for(int i =0; i< row; i++)    // rows
      {
       for(int j = 0; j < col; j++)   //columns
       {
         System.out.println("an ID "+ java.util.Arrays.deepToString(matrix));
       }
      }
     
     } // End of ReadFile method



    i just added: System.out.println("an ID "+ java.util.Arrays.deepToString(matrix)); replacing the matrix[i][j] = inputStream.nextInt(); that I had there before(what she put)

    still not working

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    The println() method does NOT read data. The code in post#9 has the code in the readFile() method that will read the contents of the file and save it in the array. AFTER that method is done filling the array, then use the println() statement to print out the contents of the array.
    The println() should NOT be inside of any loops. It will print the whole contents of the array with a single execution.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    omgitztmarie (March 11th, 2014)

  16. #15
    Junior Member
    Join Date
    Mar 2014
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: text file array help

    Quote Originally Posted by Norm View Post
    The println() method does NOT read data. The code in post#9 has the code in the readFile() method that will read the contents of the file and save it in the array. AFTER that method is done filling the array, then use the println() statement to print out the contents of the array.
    The println() should NOT be inside of any loops. It will print the whole contents of the array with a single execution.
    Ok NORM, I tried what you suggested and once again, it did not work. I tried putting the println() statement after my ReadFile() method in my FiveInARow.java class but that did not work. (BETWEEN THE ReadFile() & Process() methods). -___-

    I would really appreciate it if you really guided my through this, because what you are suggesting does not work at all. both times. Can you try to compile this in your Java compiler? Because I am usng DrJava and it is not working at all. This is very frusterating. And I cannot get anything to work. Let alone displaying my ARRAY.

    Mind you I havent even gotten to the tags yet. I thought this site was helpful learning.

    LOOK BELOW TO SEE WHERE:
    public void ReadFile()
     {
      // Initialize TAG(s) to 0
      for(int i =0; i< tag.length; i++)
        for(int j =0; i< tag.length; j++)
           tag[i][j] = 0;
     
      //Place open dialogue here
      String filePath = null;
      String fileName = null;
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogType(JFileChooser.OPEN_DIALOG );
          chooser.setDialogTitle("Open Data File");
     
             int returnVal = chooser.showOpenDialog(null);
             if( returnVal == JFileChooser.APPROVE_OPTION) 
              {
                 filePath = chooser.getSelectedFile().getPath();
                 fileName = chooser.getSelectedFile().getName();
               }
     
     
      // Define & Instantiate File
      Scanner inputStream = new Scanner(filePath);
      row  = inputStream.nextInt();
      col  = inputStream.nextInt();
     
      for(int i =0; i< row; i++)    // rows
      {
       for(int j = 0; j < col; j++)   //columns
       {
         matrix[i][j] = inputStream.nextInt();
       }
     
      }
     
     } // End of ReadFile method
     
    System.out.println("an ID "+ java.util.Arrays.deepToString(matrix));   // I TRIED TO PUT IT HERE BUT IT WONT COMPILE!!
     
     public void Process()
     {
     
      // Go through the matrix
      for(int i = 0; i < row; i++)
      {
        for(int j = 0; j < col; j++)
        {
          // Checking the matrix horizantally
          if(j <= col-5)  // Checks the boundaries of horizantal elements
     
            if (matrix[i][j] == matrix[i][j+1]
                &&(matrix[i][j+1] == matrix[i][j+2])
                &&(matrix[i][j+2] == matrix[i][j+3])
                &&(matrix[i][j+3] == matrix[i][j+4]))
     
            tag[i][j] = 1;
     
            // Checking the matrix vertically
           if(i <= row-5)  // Checks the boundaries of vertical elements
     
            if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 2;
     
           // Checking the matrix's right diagnol CHANGEEEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 3;
     
           // Checking the matrix's left diagnol   CHANGEEE
           if (matrix[i][j] == matrix[i+1][j]
                &&(matrix[i+1][j] == matrix[i+2][j])
                &&(matrix[i+2][j] == matrix[i+3][j])
                &&(matrix[i+3][j] == matrix[i+4][j]))
     
            tag[i][j] = 4;
        }
      }
     
     
     } // End of Process method

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: text file array help

    It looks like this assignment is way past your current java knowledge. There are lots of basic java coding rules that are a problem for you.
    For example:
    replacing a statement that reads data with a println() statement.
    putting a statement (the println) outside of a method.


    Move the println() statement inside of the readFile() method just before the } that ends the method.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Save array to text file
    By JGW in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 6th, 2013, 10:45 AM
  2. Reading from a text file into a two dimensional array
    By Hayfield in forum File I/O & Other I/O Streams
    Replies: 15
    Last Post: May 13th, 2012, 04:36 PM
  3. How to read a 2 dimensional text file from an array?
    By seaofFire in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 9th, 2012, 07:44 AM
  4. Text File into String Array
    By mathanv in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 12th, 2010, 05:30 AM
  5. Reading lines of a text file into a string array
    By fortune2k in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 11th, 2010, 11:56 AM

Tags for this Thread