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.
Related
I have it go through an array and assign values to it from an arraylist. I'm having trouble with trying to write a thing that can see if there are enough rows and columns for a set value in the arraylist names. everytime it prints it just prints as one line and not as row and columns with the respective numbers. I don't know what I'm doing wrong.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class SeatingChart {
public static void main(String[] args) {
// instanced variables
Scanner kb = new Scanner(System.in);
String name = "";
int r = 0;
int c = 0;
int k = 0;
String row = "";
String column = "";
ArrayList<String> names = new ArrayList<String>();
while (!name.equals("quit")) {
System.out.print("Enter first name of student: ");
// takes the name of kb and sets it to name
name = kb.nextLine();
// if the ArrayList names isEmpty then it adds the value at index
if (names.isEmpty()) {
names.add(name);
} else if (name.compareTo(names.get(names.size() - 1)) > 0) {
names.add(name);
} else {
// for loop going through the list of names to insert where it belongs
for (int i = 0; i < names.size(); i++) {
if (name.compareTo(names.get(i)) < 0) {
names.add(i, name);
i = names.size();
}
}
}
if (names.contains("quit")) {
names.remove("quit");
}
}
System.out.println(names);
// System.out.println(names);
System.out.println("how many rows do you have: ");
r = kb.nextInt();
System.out.println();
System.out.println("how many columns do you have: ");
c = kb.nextInt();
System.out.println();
System.out.println("Should students be seated row major(1) or column major(0)?");
if (kb.nextInt() == 1) {
// String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[0].length; j++) {
if (k < names.size()) {
chart[i][j] = names.get(k);
k += 1;
}
System.out.printf("%10s ", chart[i][j]);
}
}
} else if (kb.nextInt() == 2) {
String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < names.size(); i++) {
arr[i] = names.get(i);
}
System.out.println(Arrays.toString(arr));
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
arr[i] = chart[r][c];
k++;
}
}
for (int i = 0; i < chart[0].length; i++) {
for (int j = 0; j < chart.length; j++) {
System.out.printf("%10s ", chart[i][j]);
}
}
System.out.println("Column order!");
}
}
}
I have fixed one IF Block for major
if (kb.nextInt() == 1) {
// String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[0].length; j++) {
if (k < names.size()) {
chart[i][j] = names.get(k);
k += 1;
}
System.out.printf("%10s ", chart[i][j]);
}
System.out.println(""); // ADD THIS
}
}
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");
}
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 to calculate the distance between two co-ordinates, which are stored in a CVS file. There are two column mentioned in CVS files for X and Y Co-ordinates respectively.
I want to apply Euclidean Distance Formula between those stored points and printing the result on the console. For the same I have retrieved the CVS file's point as an array, printing that array on the console, and applying the Distance Formula, and after that I want to sort them according to ascending order and selecting the one having minimum distance for further problem.
But my problem is that the distance is not being displayed on the console. The code is mentioned below:
import java.util.*;
import java.io.*;
public class distance {
public void euclidianDistanceFromFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine(); // for ignoring the header of file
int row = 0;
int col = 0;
double dist;
String[][] numbers = new String[8][2];
double Cordx[] = new double[8];
double Cordy[] = new double[2];
while ((line = br.readLine()) != null && row < 8) {
StringTokenizer st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
// get next token and store it in the array
numbers[row][col] = st.nextToken();
col++;
}
col = 0;
row++;
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 2; col++) {
System.out.print(" " + numbers[row][col]);
}
System.out.println(" ");
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 2; col++) {
Cordx[row] = Double.parseDouble(numbers[row][col]);
Cordy[col] = Double.parseDouble(numbers[row][col]);
}
}
for (int i = 0; i < Cordx.length; i++) {
dist = 0;
for (int j = 0; j < Cordy.length; j++) {
double diffx = Cordx[i + 1] - Cordx[i];
double diffy = Cordy[j + 1] - Cordy[j];
dist = dist + Math.sqrt(Math.pow(diffx, 2) + Math.pow(diffy, 2));
}
System.out.println("distance is" + "" + dist);
}
}
public static void main(String[] argv) throws IOException {
try {
distance dist = new distance();
dist.euclidianDistanceFromFile("src\\ploting\\ravm.csv");
// ravm is the cvs file from which i retrieve the points and calculate the distance.
} catch (Exception e) {
e.getMessage();
}
}
}
First of all, change e.getMessage() to e.printStackTrace() and you'll be able to see that an ArrayIndexOutOfBoundsException is happening (you're trying to access an inexistent position in some array).
The error is in this loop:
for (int i = 0; i < Cordx.length; i++) {
dist = 0;
for (int j = 0; j < Cordy.length; j++) {
double diffx = Cordx[i + 1] - Cordx[i];
double diffy = Cordy[j + 1] - Cordy[j];
Note that when i is equals to Cordx.length - 1 (aka "the last position"), you try to access Cordx[i + 1] (one position after the last one), causing the error. Try to do the loops this way:
for (int i = 0; i < Cordx.length - 1; i++) {
dist = 0;
for (int j = 0; j < Cordy.length - 1; j++) {
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);
}