读取二维数组文本文件的java [英] reading 2D array text file java

查看:244
本文介绍了读取二维数组文本文件的java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开发一个基于GUI的程序从一个文本文件中读取一个矩阵的条目。第一个数字是行数;第二个数字是列数。剩下的数字是整数1和9列之间按行顺序。扫描矩阵,高亮(显示在不同颜色的条目),该水平地形成组五个单元格具有相同的值,垂直或对角线的所有单元。

我下面的程序不能正确读取该文件,我不认为,因为每次我点击我的菜单处理时间我得到的回报0的矩阵。请帮助。

类:

  // GUI相关进口进口java.awt中的*。
java.awt.event中导入*。
进口的javax.swing *。
进口java.util.Scanner中;//文件相关的进口进口java.io.FileReader; //这两者缺一
进口java.io.BufferedReader中; //为线路输入进口java.io.IOException异常;
公共类FiveInARow
{ 字节[] [] =标签新的字节[100] [100];
 INT [] []矩阵=新INT [100] [100];
 INT行;
 INT关口;
 字符串文件路径,文件名; //构造
 公共FiveInARow()
 {
  排= 0;
  COL = 0;
 } 公共无效ReadFile的()
 {
  //初始化TAG(多个)到0
  的for(int i = 0; I< tag.length;我++)
    对于(INT J = 0; I< tag.length; J ++)
       标签[I] [J] = 0;  //将在这里公开对话
  字符串文件路径= NULL;
  字符串文件名= NULL;      JFileChooser的选择器=新的JFileChooser();
      chooser.setDialogType(JFileChooser.OPEN_DIALOG);
      chooser.setDialogTitle(打开数据文件);         INT returnVal = chooser.showOpenDialog(NULL);
         如果(returnVal == JFileChooser.APPROVE_OPTION)
          {
             文件路径= chooser.getSelectedFile()的getPath()。
             文件名= chooser.getSelectedFile()的getName()。
           }
  //定义与放大器;实例文件
  扫描仪的InputStream =新的扫描仪(文件路径);
  行= inputStream.nextInt();
  COL = inputStream.nextInt();  的for(int i = 0; I<排;我++)//行
  {
   对于(INT J = 0; J<西; J ++)//列
   {
     矩阵[I] [J] = inputStream.nextInt();
   }  } } // ReadFile的方法结束 公共无效过程()
 {  //通过矩阵去
  的for(int i = 0; I<排;我++)
  {
    对于(INT J = 0; J<西; J ++)
    {
      // horizantally检查矩阵
      如果(J&下; = COL-5)//检查horizantal元件的边界        如果(矩阵[i] [j]的==矩阵[I] [J + 1]
            &放大器;及(矩阵[I] [J + 1] ==矩阵[I] [J + 2])
            &放大器;及(矩阵[I] [J + 2] ==矩阵[I] [J + 3])
            &放大器;及(矩阵[I] [J + 3] ==矩阵[I] [J + 4]))        标签[I] [J] = 1;        //垂直检查矩阵
       如果(ⅰ&下; =行-5)//检查垂直元件的边界        如果(矩阵[i] [j]的==矩阵[I + 1] [J]。
            &放大器;及(矩阵第[i + 1] [j]的==矩阵第[i + 2] [j]的)
            &放大器;及(矩阵第[i + 2] [j]的==矩阵第[i + 3] [j]的)
            &放大器;及(矩阵第[i + 3] [j]的==矩阵第[i + 4] [j]的))        标签[I] [J] = 2;       //检查矩阵的右diagnol CHANGEEEEE
       如果(矩阵[i] [j]的==矩阵[I + 1] [J]。
            &放大器;及(矩阵第[i + 1] [j]的==矩阵第[i + 2] [j]的)
            &放大器;及(矩阵第[i + 2] [j]的==矩阵第[i + 3] [j]的)
            &放大器;及(矩阵第[i + 3] [j]的==矩阵第[i + 4] [j]的))        标签[I] [J] = 3;       //检查矩阵的左diagnol CHANGEEE
       如果(矩阵[i] [j]的==矩阵[I + 1] [J]。
            &放大器;及(矩阵第[i + 1] [j]的==矩阵第[i + 2] [j]的)
            &放大器;及(矩阵第[i + 2] [j]的==矩阵第[i + 3] [j]的)
            &放大器;及(矩阵第[i + 3] [j]的==矩阵第[i + 4] [j]的))        标签[I] [J] = 4;
    }
  }
 } //处理方法结束}

DRIVER:

  // GUI相关进口进口java.awt中的*。
java.awt.event中导入*。
进口的javax.swing *。
进口java.util.Scanner中;//文件相关的进口
进口java.io.FileReader; //这两者缺一
进口java.io.IOException异常;公共类Project3Main扩展框架实现的ActionListener
{
 //文件参数
 FiveInARow F =新FiveInARow();
 字符串dataFilePath = NULL;
 字符串dataFileName = NULL;
 INT [] []数据=新INT [100] [100];
 INT [] [] TAG =新INT [100] [100];
 INT行= 0;
 INT列= 0; //检索命令code
 字符串命令=; 公共静态无效的主要(字串[] args)
 {
  帧一帧=新Project3Main();  frame.setResizable(真);
  frame.setSize(1000,700);
  frame.setVisible(真); } 公共Project3Main()
 {
  的setTitle(二维数组);  //创建菜单栏
  菜单条MB =新的菜单栏();
  setMenuBar(MB);  //创建菜单组标有文件
  菜单fileMenu =新菜单(文件);  //将它添加到菜单栏
  mb.add(fileMenu);  //创建菜单项
  //添加动作监听器
  //添加到文件菜单组
   菜单项miReadData =新菜单项(读数据);
   miReadData.addActionListener(本);
   fileMenu.add(miReadData);   菜单项miProcess =新菜单项(过程);
   miProcess.addActionListener(本);
   fileMenu.add(miProcess);   菜单项miExit =新菜单项(退出);
   miExit.addActionListener(本);
   fileMenu.add(miExit);  当窗口被关闭//程序结束
  WindowListener的L =新WindowAdapter的()
  {   公共无效的windowClosing(WindowEvent EV)
   {
    System.exit(0);
   }   公共无效的windowActivated(WindowEvent EV)
   {
    重绘();
   }   公共无效windowStateChanged(WindowEvent EV)
   {
    重绘();
   }  };  的ComponentListener K =新ComponentAdapter()
  {
   公共无效的componentResized(ComponentEvent E)
   {
          重绘();
      }
  };  //注册监听器
  this.addWindowListener(升);
  this.addComponentListener(K); }// ************ ******************************
//所谓由窗口管理器,每当应用程序窗口中执行一个动作
//(选择一个菜单项,关闭,调整大小,...
// ************ ****************************** 公共无效的actionPerformed(ActionEvent的EV)
  {
   //弄清楚这是已执行的命令
   命令= ev.getActionCommand();   //采取行动相应
   如果(读取数据.equals(命令))
   {////////////////////////////////////////////////// ///////////////调用ReadFile的方法,在你的类要做到这一点
f.ReadFile();                                dataFilePath = NULL;
    dataFileName = NULL;      JFileChooser的选择器=新的JFileChooser();
      chooser.setDialogType(JFileChooser.OPEN_DIALOG);
      chooser.setDialogTitle(打开数据文件);         INT returnVal = chooser.showOpenDialog(NULL);
         如果(returnVal == JFileChooser.APPROVE_OPTION)
          {
             dataFilePath = chooser.getSelectedFile()的getPath()。
             dataFileName = chooser.getSelectedFile()的getName()。
           }
         尝试
     {
           / *
       *扫描该文件,并把它的内容为整数的数组。
       * /
       扫描仪的InputStream =新的扫描仪(新的FileReader(dataFilePath));
       INT intLine;
       行= inputStream.nextInt();
       柱= inputStream.nextInt();
        的for(int i = 0; I<排;我++)
        {
          对于(INT J = 0; J<列; J ++)
          {            intLine = inputStream.nextInt();
          }
        }
     }     赶上(IOException异常IOE)
     {
      System.exit(0);
     }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
    重绘();
   }
   其他
    如果(过程.equals(命令))
    {
     //在类中调用工艺方法
     f.Process();
     //确定是否细胞形成一个5单元相同值的块,将它们标记在标签阵列真     重绘();
    }
   其他
    如果(退出.equals(命令))
    {
     System.exit(0);
    }  }
// ************ ********
//通过重绘称为()重绘屏幕
// ************ ********  公共无效漆(图形G)
  {   INT WW =(int)的this.getWidth();
   INT WH =(int)的this.getHeight()-40;   如果(读取数据.equals(命令))
   {
    //承认,文件打开
    如果(dataFileName!= NULL)
    {
     g.drawString(文件 - + dataFileName + - 被成功打开,WW / 2-150,WH / 2);
    }
    其他
    {
     g.drawString(无文件打开,400,400);
    }    返回;
   }
   其他
   如果(过程.equals(命令))
   {
    //显示结果
    INT X =(湿重列* 20)/ 2;
    INT Y =(WH-排* 20)/ 2;    的for(int i = 0; I<排;我++)
    {
     对于(INT J = 0; J<列; J ++)
     {
      g.setColor(Color.BLACK);
      如果(标签[i] [j]的== 1)
       g.setColor(Color.RED);
      // *******集色为其他方向      g.drawString(((整数)的数据由[i] [j]的)的toString(),X,Y。);
      X = X + 20;
     }
    X =(湿重列* 20)/ 2;
    Y = Y + 20;
    }
    返回;
   }  }}


解决方案

您文件选择会给你一个文件,你可以用你的扫描仪直接使用:

 文件chosenFile = NULL;
INT returnVal = chooser.showOpenDialog(NULL);
如果(returnVal == JFileChooser.APPROVE_OPTION)
{
    chosenFile = chooser.getSelectedFile();
}扫描仪的InputStream;
//定义与放大器;实例文件
如果(chosenFile!= NULL){
    的InputStream =新扫描仪(chosenFile);
}
其他{
    //妥善处理
}

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

  }

}

解决方案

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
}

这篇关于读取二维数组文本文件的java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆