I just want to input the matrix in the text file, but the result are clearly different. I don't have any ideas.
public void saveToTextFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("matrix.txt")));
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
writer.write(matrix[i][j] + " ");
}
writer.newLine();
}
writer.flush();
writer.close();
} catch (IOException e) {
System.out.println("Error");
}
}
I expect
1 2 3
4 5 6
7 8 9
but in the file is
1 1 1
5 5 5
9 9 9
You can try this:
int[][] ints = new int[4][4]; // Let's say you have a 4 * 4 ints array filled like this
ints[0][0] = 1;
ints[0][1] = 2;
ints[0][2] = 3;
ints[0][3] = 4;
ints[1][0] = 5;
ints[1][1] = 6;
ints[1][2] = 7;
ints[1][3] = 8;
ints[2][0] = 9;
ints[2][1] = 10;
ints[2][2] = 11;
ints[2][3] = 12;
ints[3][0] = 13;
ints[3][1] = 14;
ints[3][2] = 15;
ints[3][3] = 16;
StringBuilder sb = new StringBuilder(); // String Builder to create the table structure before writing it to the file.
for (int[] int1 : ints) {
for (int j = 0; j < int1.length; j++) {
sb.append(int1[j]).append("\t"); // Add tab to delimite the elements
}
sb.append("\r\n"); // Add new line character
}
System.out.println(sb);
Path path = Paths.get("C:\\Users\\youruser\\Documents\\test.txt"); // The path to your file
Files.write(path, sb.toString().getBytes()); // Writes to that path the bytes in the string from the stringBuilder object.
This will print the values like a table:
Slight modification to your method:
try {
int[][] matrix = new int[3][3];
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("matrix.txt")));
int num = 1;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
writer.write(matrix[i][j] + " ");
num++;
}
writer.newLine();
}
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println("Error");
}
Related
I'm trying to tally a count array to keep up with a set of 50 choices where there are three options for each choice. The count array should have 150 elements, per my instructor (3 x 50 = 150). But I keep getting an IndexOutofBounds Exception at line 55 (index = thisChoice.get(i)). I'm thinking that it must have something to do with how (or where?) I'm instantiating my count array at
line 50: int[] count = new int[students.get(0).getChoices().size()*3]
because the rest of the code came from my instructor and is presumably correct. Any ideas on what could be sending it out of bounds?
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
ArrayList<String> choices = new ArrayList<String>();
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices.add(line);
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int index, countIndex;
ArrayList<Integer> thisChoice;
int[] count = new int[students.get(0).getChoices().size()*3];
for(int i = 0; i < students.size(); i++){
countIndex = 1;
thisChoice = students.get(i).getChoices();
for(int j = 0; j < thisChoice.size(); j++){
index = thisChoice.get(i);
count[countIndex + index] = count[countIndex + index] + 1;
countIndex+=3;
}
}
// Display data.
countIndex = 1;
for(int i = 0; i < choices.size(); i+=2){
System.out.println(choices.get(i) + count[countIndex] + choices.get(i+1) + count[countIndex+1] + " Invalid: " + count[countIndex-1]);
countIndex+=3;
}
HI Please check second nested loop, it should be j instead of i .
also you haven't used int j in that loop.
for (int i = 0; i < students.size(); i++) {
countIndex = 1;
thisChoice = students.get(i).getChoices();
for (int j = 0; j < thisChoice.size(); j++) {
index = thisChoice.get(j);
count[countIndex + index] = count[countIndex + index] + 1;
countIndex += 3;
}
}
I want my program to output this in a certain way, how would I make this possible? So far, my code is giving me the wrong thing.
Here's my .txt file:
ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO
Here's my java file:
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
String line = in.readLine();
char[][] table = new char[6][5];
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
while(table[i][j] < 6) {
table[i][j] = line.charAt(j);
}
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.println(table[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
How would I print this .txt file like so:
ABCDE
GHIJK
MNOPQ
STUVW
XYZOO
OOOOO
A couple of problems
see
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
char[][] table = new char[6][5];
int counter = 0;
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
table[i][j] = line.charAt(counter++); // need to increment through the String
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(table[i][j] + " "); // not println
}
System.out.println();
}
output
A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
Z O O O O
Although a more extensible way would be link
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
String lines [] = line.split("(?<=\\G.....)");
for (String l : lines) {
System.out.println(l);
}
For this intro-level assignment, I have to set up a 2D multidimensional array from a file and from a double[][] a and apply several methods to them. For now, I'm mostly concerned with simply initializing the arrays. I'm trying to figure out a way to take a test file, read the first int as the number of rows, the first integer of each line as the number of columns per row, and each double as a member of the array.
public class MDArray
{
static int rowCount;
static int columnCount;
private static double[][] mdarray = new double[rowCount][columnCount];
public MDArray(double[][] a)
{
mdarray = a;
}
public MDArray(String file)
{
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
while(input.hasNextDouble())
{
rowCount = input.nextInt();
for(int i = 0; i < rowCount; i++)
{
columnCount = input.nextInt();
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
}
}
public static boolean isRagged()
{
for(int i = 0; i < mdarray.length; i++)
{
int rowLength1 = mdarray.length;
for(int j = i + 1; j < mdarray.length; j++)
{
int rowLength2 = mdarray.length;
if(rowLength1 != rowLength2)
{
return true;
}
}
}
return false;
}
public static int getNumberOfRows()
{
int numRows = 0;
for(int i = 0; i < mdarray.length; i++)
{
numRows++;
}
return numRows;
}
public static int getNumberOfCols()
{
int numCols = 0;
for(int i = 0, j = i + 1; i < mdarray.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i].length > mdarray[j].length)
{
numCols++;
}
}
}
return numCols;
}
public static double getValAt(int i, int j)
{
if(i > mdarray.length || j > mdarray[i].length)
{
double invalid = Double.NaN;
return invalid;
}
double valAt = mdarray[i][j];
return valAt;
}
public static void sort(boolean byColumn)
{
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
}
}
}
}
}
}
public static int hamming(boolean byColumn)
{
int hamVal = 0;
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
hamVal++;
}
}
}
}
}
return hamVal;
}
public static double[] max()
{
double[] maxVal = new double[mdarray.length];
for(int i = 0, j = i + 1; i < maxVal.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i][k] > mdarray[j][k])
{
maxVal = mdarray[i];
}
}
}
return maxVal;
}
public String toString()
{
String arrayString = "";
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
arrayString += ", " + mdarray[i][j];
}
arrayString = arrayString + "/n";
}
return arrayString;
}
}
This was the file I was testing the MDArray(String file) with:
3
2 4.1 8.9
5 9.5 2.0 7.3 2.1 8.9
3 1.3 5.2 3.4
I think the problem is that the rowCount and columnCount integers are not initialized, but I'm not sure how to initialize them to a variable length with basic array skills. This is also affecting the other constructor as well. Being an intro-level course, I am not supposed to use more advanced techniques such as ArrayList. In addition, I can't verify if the methods are correct, since I don't have an array to test them with.
EDIT: While I did implement many of the suggestions in the answers, such as changing everything to non-static and other changes, I'm still getting a NullPointerException for the line mdarray[i][j] = input.nextDouble();. I assume it has to do with the private double[][] mdarray, which is required in the assignment specifications. Now I'm trying to find a way to initialize it such that it can be overridden in the later methods.
You have to initialize the array in your constructor, since that's when you know the dimensions :
public MDArray(String file)
{
Scanner input = null;
try {
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e) {
System.out.println("File Not Found.");
System.exit(0);
}
rowCount = input.nextInt();
mdarray = new double[rowCount][]; // init the array
for(int i = 0; i < rowCount; i++) {
columnCount = input.nextInt();
mdarray[i] = new double[columnCount]; // init the current row
for(int j = 0; j < columnCount; j++) {
mdarray[i][j] = input.nextDouble();
}
}
}
You could initialize your arrays by putting the amount of rows and columns on the first 2 lines of your multidimensional array, if i had 10 rows and 12 columns i could do something like this:
public void arrayStuff() {
File fileToRead = new File("YOUR LINK HERE");
String[][] data;
try (BufferedReader reader = new BufferedReader(new FileReader(fileToRead))) {
String line;
data = new String[Integer.parseInt(reader.readLine())][Integer.parseInt(reader.readLine())];
while((line = reader.readLine()) != null) {
// read the rest here..
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using an AutoCloseable (which is why the try is between these ()'s, but this is so that i don't have to close it afterwards.
Basically, first i read the amount of rows there are and then the amount of columns there are, so if i had this file:
10
12
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
It'd be able to read all of this, because the amount of rows and columns were defined in the file.
You don't use the fields rowCount and columnCount: you can remove them
The mdarray field should be non-static, so should be the methods that use them (if it was a utility class, you wouldn't have any constructor)
The arrays can be created while reading the file:
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
int rowCount = input.nextInt();
mdarray = new double[rowCount][];
for(int i = 0; i < rowCount; i++)
{
int columnCount = input.nextInt();
mdarray[i] = new double[columnCount];
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
methods getNumberOfRows() and getNumberOfCols() count be much simpler:
public int getNumberOfRows()
{
return mdarray.length;
}
public int getNumberOfCols() {
int result = 0;
for (double[] col: mdarray) {
if (col.length > result) {
result = col.length;
}
}
return result;
}
In getValueAt(), the test is wrong; it should be:
if(i >= mdarray.length || j >= mdarray[i].length)
This is one first post here, Pardon me if my question doesn't meet required standards here.
I have written a piece of code which takes input for two matrix from two separate files and performs multiplication and output the data to a new file.
It gives perfect output for 2x3 or 3x3 matrix. If i give input of 4x4 matrix i get array index out of bound runtime exception. I don't understand the reason as i dynamically create index
I get an array index out of bound exception at line 40.
I get an error.
![Snipet][2]
List item
public class MM {
private BufferedReader br;
private int sum = 0;
private final static String matrixA="matrixA.txt";
private final static String matrixB="matrixB.txt";
public static void main(String[] args) {
new MM().MathMultiplicationValues(matrixA, matrixB);
}
private void MathMultiplicationValues(String mat1, String mat2) {
try {
br = new BufferedReader(new FileReader(mat1));
String line;
int mat1rows = 0, mat1cols = 0, mat2rows = 0, mat2cols = 0;
while ((line = br.readLine()) != null) {
mat1cols = line.split(" ").length + 1;
mat1rows++;
}
br.close(); // To close file
br = new BufferedReader(new FileReader(mat2)); // to read input from file.
while ((line = br.readLine()) != null) {
mat2cols = line.split(" ").length + 1;
mat2rows++;
}
int[][] mat1vals = new int[mat1rows ][mat1cols ];
int[][] mat2vals = new int[mat2rows ][mat2cols ];
br.close();
br = new BufferedReader(new FileReader(mat1));
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
br = new BufferedReader(new FileReader(mat2));
for (int i = 1; i < mat2rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat2cols; j++) {
mat2vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
if ((mat1cols-1) == mat2rows) {
int[][] resltmat = new int[mat1rows + 1][mat2cols + 1];
for (int i = 1; i < mat1rows + 1; i++) { //Loop does matrix multiplication.
for (int j = 1; j < mat1cols; j++) {
for (int k = 0; k < mat2rows + 1; k++)
sum = sum + mat1vals[i][k] * mat2vals[k][j];
resltmat[i][j] = sum;
sum = 0;
}
}
final PrintWriter pw = new PrintWriter("Answer.txt"); //Creates a new file called Matrix Answer.
for (int i = 1; i < mat1rows + 1; i++)
{
for (int j = 1; j < mat2cols; j++) {
pw.print(resltmat[i][j] + " "); // Writes the output to file the file called MatrixAnswer
}
pw.println();
}
pw.close();
} else // If no of columns not equal to rows control passes to else block.
System.out.println("Multiplication of Matrix is not possible because columns are not equal to rows");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Might be because of this
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
i = mat1rows on the last iteration which is OOB. Change for (int i = 1; i < mat1rows + 1; i++) to for (int i = 1; i < mat1rows; i++)
As you used in the allocation, the dimension of the resulting matrix are mat1rows x mat2cols. Thus in the computation of resltmat[i][j] the index i has bound mat1rows (check) and the index j has the upper bound mat2cols (fail). Thus change the range of j from mat1cols to mat2cols.
I am having some trouble with a Java program. I have a txt data file, which I will display, that I need to add into two separate arrays. The text file is 8 lines long that is supposed to go into two separate 4x4 matrices. A little background info on this program, reads in two arrays, compares them and outputs the largest elements of the same index and outputs them in a separate array. I somehow cannot seem to figure out how to add the data file into two separate arrays. My code is below, thanks in advance.
Data File:
2 7 6 4
6 1 2 4
9 7 2 6
8 3 2 1
4 1 3 7
6 2 3 8
7 2 2 4
4 2 3 1
Code:
public class prog465a
{
public static void main(String[] args) {
Scanner inFile = null;
try
{
inFile = new Scanner(new File("prog465a.dat.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File not found!");
System.exit(0);
}
int[][] firstData = new int[4][4];
int[][] secondData = new int[4][4];
int[][] finalData = new int[4][4];
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
{
if (i < 4 && j < 4){ //Trying to add first four lines to one matrix
firstData[i][j] = inFile.nextInt();
} else if (i >= 4 && j >= 4)
{
secondData[i][j] = inFile.nextInt();
}
}
}
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
{
if (firstData[i][j] >= secondData[i][j])
{
firstData[i][j] = finalData[i][j];
}
else if (secondData[i][j] >= firstData[i][j])
{
secondData[i][j] = finalData[i][j]
}
}
}
for ( int c = 0 ; c < finalData.length ; c++ )
{
for ( int d = 0 ; d < finalData.length ; d++ )
{
System.out.print(finalData[c][d]+" ");
}
System.out.print("\n");
}
}
}
The problems is that you are trying to parse a file with 8 rows and 8 column..
change this:
int[][] finalData = new int[4][4];
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
to:
int[][] finalData = new int[4][4];
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 4; j++)
that means 8 rows of file with 4 column each.
Also on the second part of your forloop again you are trying to get 8x8 matrix it should be 4x4..
change:
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
{
if (firstData[i][j] >= secondData[i][j])
{
firstData[i][j] = finalData[i][j];
}
else if (secondData[i][j] >= firstData[i][j])
{
secondData[i][j] = finalData[i][j]
}
}
}
to:
for (int i = 0; i< 4; i++)
{
for(int j = 0; j < 4; j++)
{
if (firstData[i][j] >= secondData[i][j] )
{
finalData[i][j] = firstData[i][j];
}
else if (secondData[i][j] >= firstData[i][j])
{
finalData[i][j] = secondData[i][j] ;
}
}
}