• Курсы Академии Кодебай, стартующие в мае - июне, от команды The Codeby

    1. Цифровая криминалистика и реагирование на инциденты
    2. ОС Linux (DFIR) Старт: 16 мая
    3. Анализ фишинговых атак Старт: 16 мая Устройства для тестирования на проникновение Старт: 16 мая

    Скидки до 10%

    Полный список ближайших курсов ...

Проблема Как вывести матрицу любого размера в текстовом файле?

  • Автор темы nastya2018
  • Дата начала

sinner67

Green Team
24.03.2017
279
357
BIT
0
Не знаю мне сказали написать метод который просто сохраняет мою матрицу в файл(
Смотри как просто получается:
Java:
public void writeMatrixToFile(Matrix m, String filename) throws Exception{
    JSONArray ar = new JSONArray();
    FileWriter writer = new FileWriter(filename);

    for (int i = 0; i < m.length; i++){
        JSONArray newAr = new JSONArray();
        for (int j = 0; j < m.length; j++){
            newAr.add(m[i][j]);
        }
        ar.add(newAr);
    }

    String jsonStr = ar.toJSONString();
        
    writer.write(jsonStr);
    writer.flush();
    writer.close();
}

Без джейсона можно так:
Java:
public static void writeMatrixToFile(Matrix m, String filename) throws Exception{

        String strForWrite = "";
        FileWriter writer = new FileWriter(filename);

        for (int i = 0; i < m.length; i++){
            for (int j = 0; j < m.length; j++){
                strForWrite += m[i][j] + " ";
            }
            strForWrite += "\n";
        }

        writer.write(strForWrite);
        writer.flush();
        writer.close();
    }

но этот вариант более проблематичен если нужно будет обратно загрузить матрицу.
так же можно попробовать написать доп йункцию для преодразования массива в строку, потипу джейсона, тогда с загрузкой из файла не будет проблем.
 
  • Нравится
Реакции: Vertigo
N

nastya2018

Без джейсона можно так:
Java:
public static void writeMatrixToFile(Matrix m, String filename) throws Exception{

        String strForWrite = "";
        FileWriter writer = new FileWriter(filename);

        for (int i = 0; i < m.length; i++){
            for (int j = 0; j < m.length; j++){
                strForWrite += m[i][j] + " ";
            }
            strForWrite += "\n";
        }

        writer.write(strForWrite);
        writer.flush();
        writer.close();
    }

но этот вариант более проблематичен если нужно будет обратно загрузить матрицу.
так же можно попробовать написать доп йункцию для преодразования массива в строку, потипу джейсона, тогда с загрузкой из файла не будет проблем.

почему ошибка в ней((
 

Вложения

  • Безымянный.png
    Безымянный.png
    160 КБ · Просмотры: 591
N

nastya2018

перепеши ее в одтельную функцию. Мистика какая то, вроде все исключения проверяешь.
Пробрось все исключения: throws Exception

У меня ни на что не ругается:Посмотреть вложение 21133
Код:
package matrix;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class MatrixUtils {

    public static void fillByRandom(Matrix m) {
        int rowCount = m.getRowCount();
        int colCount = m.getColCount();
        Random random = new Random();

        for (int i = 1; i <= rowCount; i++) {

            for (int j = 1; j <= colCount; j++) {
                try {
                    m.put(i, j, random.nextInt(50));
                } catch (MatrixIndexException e) {
                    System.err.println(e.getMessage());

                }

            }
        }
    }

    public static void fillByNumber(Matrix m, int number) {
        int rowCount = m.getRowCount();
        int colCount = m.getColCount();

        for (int i = 1; i <= colCount; i++) {

            for (int j = 1; j <= rowCount; j++) {
                try {
                    m.put(i, j, number);

                } catch (MatrixIndexException e) {
                    System.err.println(e.getMessage());

                }

            }
        }

    }

    public static Matrix fillByKeyboard() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter The Number Of Matrix Rows:");
        int rowCount = scan.nextInt();
        System.out.println("Enter The Number Of Matrix Columns:");
        int colCount = scan.nextInt();
        try {
            Matrix2D m = new Matrix2D(rowCount, colCount);
            System.out.println("Enter Matrix Data:");
            for (int i = 1; i <= rowCount; i++) {
                for (int j = 1; j <= colCount; j++) {
                    int value = scan.nextInt();
                     m.put(i, j, value);
                }
            }
            return m;

        } catch (MatrixIndexException ex) {
            System.err.println(ex.getMessage());

        }
        return null;

    }
    
     public static Matrix MatrixMultiple(Matrix a, Matrix b) throws MatrixIndexException {
      
        int aRows = a.getRowCount();
        int aColumns = a.getColCount();
        int bRows = b.getRowCount();
        int bColumns = b.getColCount();

        if (aColumns != bRows) {
            throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
        }

        Matrix2D c = new Matrix2D(aRows, bColumns);
        for (int i = 0; i < aRows; i++) {
            for (int j = 0; j < bColumns; j++) {
                c.put(i+1,j+1,0);
            }
        }

        for (int i = 0; i < aRows; i++) {
            for (int j = 0; j < bColumns; j++) {
                for (int k = 0; k < aColumns; k++) {
                    c.put(i+1,j+1,c.get(i+1,j+1) + a.get(i+1, k+1) * b.get(k+1, j+1));
                }
            }
        }

        return c;   

        
    }
     public static void writeMatrixToFile(Matrix m, String filename) throws MatrixIndexException, IOException{

        String strForWrite = "";
        try (FileWriter writer = new FileWriter(filename)) {
            for (int i = 0; i < m.length; i++){
                for (int j = 0; j < m.length; j++){
                    strForWrite += m[i][j] + " ";
                }
                strForWrite += "\n";
            }

            writer.write(strForWrite);
            writer.flush();
        }
    }

Я же правильно написала?
 

sinner67

Green Team
24.03.2017
279
357
BIT
0
Код:
package matrix;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class MatrixUtils {

    public static void fillByRandom(Matrix m) {
        int rowCount = m.getRowCount();
        int colCount = m.getColCount();
        Random random = new Random();

        for (int i = 1; i <= rowCount; i++) {

            for (int j = 1; j <= colCount; j++) {
                try {
                    m.put(i, j, random.nextInt(50));
                } catch (MatrixIndexException e) {
                    System.err.println(e.getMessage());

                }

            }
        }
    }

    public static void fillByNumber(Matrix m, int number) {
        int rowCount = m.getRowCount();
        int colCount = m.getColCount();

        for (int i = 1; i <= colCount; i++) {

            for (int j = 1; j <= rowCount; j++) {
                try {
                    m.put(i, j, number);

                } catch (MatrixIndexException e) {
                    System.err.println(e.getMessage());

                }

            }
        }

    }

    public static Matrix fillByKeyboard() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter The Number Of Matrix Rows:");
        int rowCount = scan.nextInt();
        System.out.println("Enter The Number Of Matrix Columns:");
        int colCount = scan.nextInt();
        try {
            Matrix2D m = new Matrix2D(rowCount, colCount);
            System.out.println("Enter Matrix Data:");
            for (int i = 1; i <= rowCount; i++) {
                for (int j = 1; j <= colCount; j++) {
                    int value = scan.nextInt();
                     m.put(i, j, value);
                }
            }
            return m;

        } catch (MatrixIndexException ex) {
            System.err.println(ex.getMessage());

        }
        return null;

    }
   
     public static Matrix MatrixMultiple(Matrix a, Matrix b) throws MatrixIndexException {
     
        int aRows = a.getRowCount();
        int aColumns = a.getColCount();
        int bRows = b.getRowCount();
        int bColumns = b.getColCount();

        if (aColumns != bRows) {
            throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
        }

        Matrix2D c = new Matrix2D(aRows, bColumns);
        for (int i = 0; i < aRows; i++) {
            for (int j = 0; j < bColumns; j++) {
                c.put(i+1,j+1,0);
            }
        }

        for (int i = 0; i < aRows; i++) {
            for (int j = 0; j < bColumns; j++) {
                for (int k = 0; k < aColumns; k++) {
                    c.put(i+1,j+1,c.get(i+1,j+1) + a.get(i+1, k+1) * b.get(k+1, j+1));
                }
            }
        }

        return c;  

       
    }
     public static void writeMatrixToFile(Matrix m, String filename) throws MatrixIndexException, IOException{

        String strForWrite = "";
        try (FileWriter writer = new FileWriter(filename)) {
            for (int i = 0; i < m.length; i++){
                for (int j = 0; j < m.length; j++){
                    strForWrite += m[i][j] + " ";
                }
                strForWrite += "\n";
            }

            writer.write(strForWrite);
            writer.flush();
        }
    }
catch забыла
 
  • Нравится
Реакции: Vertigo
N

nastya2018

Код:
 public static void writeMatrixToFile(Matrix m, String filename) throws MatrixIndexException, IOException{

        String strForWrite = "";
        try (FileWriter writer = new FileWriter(filename)) {
            for (int i = 0; i < m.length; i++){
                for (int j = 0; j < m.length; j++){
                    strForWrite += m[i][j] + " ";
                }
                strForWrite += "\n";
            }

           }catch(MatrixIndexException e)
           writer.write(strForWrite);
            writer.flush();
        }
    }
 

sinner67

Green Team
24.03.2017
279
357
BIT
0
Да и смысл трайкетчи ставить если все пробрасываешь?
 
N

nastya2018

почти) или все лови в трайкетчи или пробрасывай ненужные. А то ты MatrixIndexException ловишь, но в то же время пробрасываешь
как можно правильно написать( я просто только учусь. извините что иногда туплю(
 

sinner67

Green Team
24.03.2017
279
357
BIT
0
А в нетбинсе разве не пишется на что он ругается?
 

sinner67

Green Team
24.03.2017
279
357
BIT
0
Извини, я тут тебя видимо в заблуждение ввожу. Дело в том, что я свой пример воспроизводил на двумерном массиве. А у тебя матрица, свой класс. У тебя в классе должен быть метод для проверки размера матрицы, аналогичный методу length в массивах, и обращение к элементам матрицы

покажи класс Matrix свой
 
N

nastya2018

покажи класс Matrix свой
Код:
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package matrix;

public abstract class Matrix extends Exception {

    public abstract int get(int i, int j) throws MatrixIndexException;

    public abstract void put(int i, int j, int value) throws MatrixIndexException;

    public abstract int getRowCount();

    public abstract int getColCount();

    @Override
    public String toString() {
        StringBuilder out = new StringBuilder();
        out.append("Matrix:\n[ ");

        for (int i = 0; i < getRowCount(); i++) {
            if (i != 0) {
                out.append("\n");
                out.append("  ");
            }
            for (int j = 0; j < getColCount(); j++) {
                try {
                    out.append(this.get(i + 1, j + 1));
                    out.append(" ");
                } catch (MatrixIndexException e) {

                }
                if (j == getColCount() - 1) {

                    out.append(" ]");
                }

            }
        }

        return out.toString();

    }

    @Override
    public boolean equals(Object obj) {
        Matrix m = (Matrix) obj;
        if (m.getRowCount() != getRowCount() || m.getColCount() != getColCount()) {
            return false;
        }

        for (int i = 0; i < getRowCount(); i++) {
            for (int j = 0; j < getColCount(); j++) {
                try {
                    if (this.get(i + 1, j + 1) != m.get(i + 1, j + 1)) {
                        return false;
                    }
                } catch (MatrixIndexException ex) {

                }
            }
        }

        return true;
    }

}

покажи класс Matrix свой
от класса Matrix наследуется Matrix1D (одномерный массив) и Matrix2D ( двумерный массив)

от класса Matrix наследуется Matrix1D (одномерный массив) и Matrix2D ( двумерный массив)
Matrix 1D
Код:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package matrix;

public class Matrix1D extends Matrix {

    private int rowCount;
    private int colCount;
    private int[] data;

    Matrix1D(int row, int col) throws MatrixIndexException {
        if (row <= 0 || col <= 0) {
            throw new MatrixIndexException("Недопустимый размер матрицы.");
        }
        this.rowCount = row;
        this.colCount = col;
        data = new int[row * col];
    }

    Matrix1D(Matrix1D matrix) {

        this.rowCount = matrix.getRowCount();
        this.colCount = matrix.getColCount();
        data = new int[rowCount * colCount];

        for (int i = 1; i < rowCount; i++) {
            for (int j = 1; j < colCount; j++) {
                data[i * colCount + j] = matrix.data[i * colCount + j];
            }
        }
    }

    public int get(int i, int j) throws MatrixIndexException {
        if (i < 1 || i > rowCount) {
            throw new MatrixIndexException("Недопустимое число строк: " + i);
        }
        if (j < 1 || j > colCount) {
            throw new MatrixIndexException("Недопустимое число столбцов: " + j);
        }

        return data[(i - 1) * colCount + j - 1];
    }

    public void put(int i, int j, int value) throws MatrixIndexException {
        if (i < 0 || i > rowCount) {
            throw new MatrixIndexException("Недопустимое число строк: " + i);
        }
        if (j < 0 || j > colCount) {
            throw new MatrixIndexException("Недопустимое число столбцов: " + j);
        }
        data[(i - 1) * colCount + j - 1] = value;

    }

    public int getRowCount() {
        return rowCount;
    }

    public int getColCount() {
        return colCount;
    }

    /*@Override
    public boolean equals(Object obj) {
        Matrix1D m = (Matrix1D) obj;

        if (m.getRowCount() != rowCount || m.getColCount() != colCount) {
            return false;
        }

        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < colCount; j++) {
                if (data[i * colCount + j] != m.data[i * colCount + j]) {
                    return false;
                }
            }
        }

        return true;
    }*/

    /*@Override
    public String toString() {
        StringBuilder out = new StringBuilder();
        out.append("Matrix:\n[ ");
        for (int i = 0; i < rowCount; i++) {
            if (i != 0) {
                out.append("\n");
                out.append("  ");
            }
            for (int j = 0; j < colCount; j++) {
                out.append(data[i * colCount + j]);
                if (j == colCount - 1) {
                    continue;
                }
                for (int k = 0; k < getMaxLength() - getIntLength(data[i * colCount + j]) + 2; k++) {
                    out.append(" ");
                }
            }
        }
        out.append("  ]");
        return out.toString();
    }*/
    

    private int getMaxLength() {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < colCount; j++) {
                int k = data[i * colCount + j];
                if (k > max) {
                    max = k;
                }
            }
        }
        return getIntLength(max);
    }
    

    private int getIntLength(int i) {
        return String.valueOf(i).length();

    }
}
 

sinner67

Green Team
24.03.2017
279
357
BIT
0
Java:
public static void writeMatrixToFile(Matrix m, String filename) {


        try(FileWriter writer = new FileWriter(filename, false)){
            String strForWrite = "";


            for (int i = 0; i < m.getRowCount(); i++){
                for (int j = 0; j < m.getColCount(); j++){
                    strForWrite += m.get(i,j) + " ";
                }
                strForWrite += "\n";
            }

            writer.write(strForWrite);
            writer.flush();
        }catch (IOException e){
            e.printStackTrace();
        }catch(MatrixIndexException e){
             e.printStackTrace();
        }
    }

вот такая функция
 
N

nastya2018

Matrix 2D
Код:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package matrix;

public class Matrix2D extends Matrix {
    
 
    private int rowCount;
    private int colCount;
    private int[][] data;

    

    Matrix2D(int row, int col) throws MatrixIndexException {
        if (row <= 0 || col <= 0) {
            throw new MatrixIndexException("Недопустимый размер матрицы.");
        }
        this.rowCount = row;
        this.colCount = col;
        data = new int[row][col];
    }

    Matrix2D(Matrix2D matrix) {

        this.rowCount = matrix.getRowCount();
        this.colCount = matrix.getColCount();
        data = new int[rowCount][colCount];

        for (int i = 1; i < rowCount; i++) {
            for (int j = 1; j < colCount; j++) {
                data[i][j] = matrix.data[i][j];
            }
        }
    }

    public int get(int i, int j) throws MatrixIndexException {
        if (i < 1 || i > rowCount) { 
            throw new MatrixIndexException("Недопустимое число строк: " + i);
        }
        if (j < 1 || j > colCount) {
            throw new MatrixIndexException("Недопустимое число столбцов: " + j);
        }
        
        return data [i-1][j-1];
    }

    public void put(int i, int j, int value) throws MatrixIndexException {
        if (i < 1 || i > rowCount) {
            throw new MatrixIndexException("Недопустимое число строк: " + i);
        }
        if (j < 1 || j > colCount) {
            throw new MatrixIndexException("Недопустимое число столбцов: " + j);
        }
        data[i-1][j-1] = value;


    }

    public int getRowCount() {
        return rowCount;
    }

    public int getColCount() {
        return colCount;
    }

    /*@Override
    public boolean equals(Object obj) {
        Matrix2D m = (Matrix2D) obj;

        if (m.getRowCount() != rowCount || m.getColCount() != colCount) {
            return false;
        }

        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < colCount; j++) {
                if (data[i][j] != m.data[i][j]) {
                    return false;
                }
            }
        }

        return true;
    }*/

    /*@Override
     public String toString() {
        StringBuilder out = new StringBuilder();
        out.append("Matrix:\n[ ");
        for (int i = 0; i < rowCount; i++) {
            if (i != 0) {
                out.append("\n");
                out.append("  ");
            }
            for (int j = 0; j < colCount; j++) {
                out.append(data[i][j]);
                if (j == colCount - 1) {
                    continue;
                }
                for (int k = 0; k < getMaxLength() - getIntLength(data[i][j]) + 2; k++) {
                    out.append(" ");
                }
            }
        }
        out.append("  ]");
        return out.toString();
    }*/

    private int getMaxLength() {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < colCount; j++) {
                int k = data[i][j];
                if (k > max) {
                    max = k;
                }
            }
        }
        return getIntLength(max);
    }

    private int getIntLength(int i) {
        return String.valueOf(i).length();
    }

}

Java:
public static void writeMatrixToFile(Matrix m, String filename) {


        try(FileWriter writer = new FileWriter(filename, false)){
            String strForWrite = "";


            for (int i = 0; i < m.getRowCount(); i++){
                for (int j = 0; j < m.getColCount(); j++){
                    strForWrite += m.get(i,j) + " ";
                }
                strForWrite += "\n";
            }

            writer.write(strForWrite);
            writer.flush();
        }catch (IOException e){
            e.printStackTrace();
        }catch(MatrixIndexException e){
             e.printStackTrace();
        }
    }

вот такая функция

Спасибо вам большое))) я вам очень благодарна можете пожалуйста если не сложно написать последний метод loadMatrixFromFile(filename) написать пожалуйста. Надо из файла достать теперь. Я вам буду очень благодарна
 
  • Нравится
Реакции: Vertigo
N

nastya2018

Java:
public static void writeMatrixToFile(Matrix m, String filename) {


        try(FileWriter writer = new FileWriter(filename, false)){
            String strForWrite = "";


            for (int i = 0; i < m.getRowCount(); i++){
                for (int j = 0; j < m.getColCount(); j++){
                    strForWrite += m.get(i,j) + " ";
                }
                strForWrite += "\n";
            }

            writer.write(strForWrite);
            writer.flush();
        }catch (IOException e){
            e.printStackTrace();
        }catch(MatrixIndexException e){
             e.printStackTrace();
        }
    }

вот такая функция

Можете помочь с послденим методом пожалуйста
 

sinner67

Green Team
24.03.2017
279
357
BIT
0
Вот о чем я и говорил)) С джейсоном небыло бы проблем.
Java:
public Matrix loadMatrixFromFile(String filename){
        try(FileReader reader = new FileReader(filename)){
            String strFromFile = "";

            while (reader.ready()){
                strFromFile += (char)reader.read();
            }

            String[] arr = strFromFile.split(" |\n");
            Matrix result = new Matrix(Integer.valueOf(arr[0]),Integer.valueOf(arr[1]));

            int row = 0;
            int col = 0;

            for (int i = 2; i < arr.length; i++){
                if (!arr[i].equals("")){
                    result.put(row, col) = Integer.valueOf(arr[i]);
                    col++;
                    if (col == result.getColCount()){
                        col = 0;
                        row++;
                    }
                }
            }

            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

Но и для функции сохранения в файл надо сделать изменения:
Java:
public static void writeMatrixToFile(Matrix m, String filename) {


        try(FileWriter writer = new FileWriter(filename, false)){
            String strForWrite = "";
            
            writer.write(String.valueOf(m.getRowCount()));
            writer.write("\n");
            writer.write(String.valueOf(m.getColCount()));
            writer.write("\n");

            for (int i = 0; i < m.getRowCount(); i++){
                for (int j = 0; j < m.getColCount(); j++){
                    strForWrite += m.get(i,j) + " ";
                }
                strForWrite += "\n";
            }

            writer.write(strForWrite);
            writer.flush();
        }catch (IOException e){
            e.printStackTrace();
        }catch(MatrixIndexException e){
             e.printStackTrace();
        }
    }

Должно работать
 
N

nastya2018

Вот о чем я и говорил)) С джейсоном небыло бы проблем.
Java:
public Matrix loadMatrixFromFile(String filename){
        try(FileReader reader = new FileReader(filename)){
            String strFromFile = "";

            while (reader.ready()){
                strFromFile += (char)reader.read();
            }

            String[] arr = strFromFile.split(" |\n");
            Matrix result = new Matrix(Integer.valueOf(arr[0]),Integer.valueOf(arr[1]));

            int row = 0;
            int col = 0;

            for (int i = 2; i < arr.length; i++){
                if (!arr[i].equals("")){
                    result.put(row, col) = Integer.valueOf(arr[i]);
                    col++;
                    if (col == result.getColCount()){
                        col = 0;
                        row++;
                    }
                }
            }

            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

Но и для функции сохранения в файл надо сделать изменения:
Java:
public static void writeMatrixToFile(Matrix m, String filename) {


        try(FileWriter writer = new FileWriter(filename, false)){
            String strForWrite = "";
           
            writer.write(String.valueOf(m.getRowCount()));
            writer.write("\n");
            writer.write(String.valueOf(m.getColCount()));
            writer.write("\n");

            for (int i = 0; i < m.getRowCount(); i++){
                for (int j = 0; j < m.getColCount(); j++){
                    strForWrite += m.get(i,j) + " ";
                }
                strForWrite += "\n";
            }

            writer.write(strForWrite);
            writer.flush();
        }catch (IOException e){
            e.printStackTrace();
        }catch(MatrixIndexException e){
             e.printStackTrace();
        }
    }

Должно работать

Эта для чтения из файла в программу?
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!