reading 2D array text file java

2019-08-16 04:55发布

问题:

I am trying to 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.

My program below is NOT reading the file correctly I don't think because every time I click Process in my menu I get in return a matrix of 0's. PLEASE HELP.

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:

    // 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
f.ReadFile();



                                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; 
   }

  }

}

回答1:

The problem is this line:

Scanner inputStream = new Scanner(filePath);

filePath is a String. Scanner accepts a String in its constructor, but then it treats the String as the source. It'll never load the file.

You need to pass it an InputStream or a File or something else as you do in the Driver.



回答2:

Your file chooser will give you a file you can use directly with your scanner:

File chosenFile = null;
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION) 
{
    chosenFile =  chooser.getSelectedFile();
}

Scanner inputStream;
// Define & Instantiate File
if (chosenFile != null) {
    inputStream = new Scanner(chosenFile);
} 
else {
    // handle appropriately
}


回答3:

Change your use of the scanner to be like this:

Scanner inputStream  = = new Scanner(new File("filename"));;
String line = scanner.nextLine();
String[] numbers = line.split(" "); 
for(String str : numbers){
  int nunber = Interger.parseInt(str);
}

This will read one line of the file at a time, split it on spaces (getting the numbers by themselves) then changing them from a string to a int. I think its getting strings and thus nextInt() has no values and picks up the default.