读取2D数组文本文件java

时间:2014-03-11 22:28:17

标签: java arrays file text readfile

我正在尝试开发一个基于GUI的程序来从文本文件中读取矩阵的条目。第一个数字是行数;第二个数字是列数。其余数字是逐行排序的1到9之间的整数。扫描矩阵,突出显示(以不同颜色显示条目)所有细胞,这些细胞形成一组五个细胞,水平,垂直或对角具有相同的值。

我的程序下面没有正确读取文件我不会想,因为每次我点击菜单中的处理,我都会得到一个0的矩阵。请帮助。

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

  }

}

3 个答案:

答案 0 :(得分:1)

问题在于这一行:

Scanner inputStream = new Scanner(filePath);

filePath是一个String。 Scanner在其构造函数中接受String,但随后它将String视为源。它永远不会加载文件。

您需要像在Driver中一样传递InputStream或File或其他内容。

答案 1 :(得分:1)

您的文件选择器会为您提供一个文件,您可以直接使用扫描仪:

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
}

答案 2 :(得分:0)

将您对扫描仪的使用更改为:

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

这将一次读取文件的一行,将其拆分为空格(自己获取数字),然后将它们从字符串更改为int。我认为它获取字符串因此nextInt()没有值并且获取默认值。