Reading two matrices from the same file in java - java

Hello guys and thank you in advance for your help!
I am trying to do a matrice calculator in java
that reads two matrices from the same file like this:
2 2
34 78
89 -12
#
2 2
67 76
123 5
first line is the rank
second and third line are the first matrix
the "#" splits the first and the second matrix
and that's the code I came up with and I didn't
find anything similar to this problem... can someone help me please?
String [] line = new String[30];
int counter = 2;
int rank[] = new int[2];
int matrixa[][] = new int [3][3];
try {
BufferedReader MyReader = new BufferedReader(new FileReader("matrix.txt"));
while(line != null) {
line = MyReader.readLine().split(" ");
}
rank[0] = Integer.parseInt(line[0]);
rank[1] = Integer.parseInt(line[1]);
for(int i = 0; i <rank[0];i++) {
for (int j=0;j<rank[1];j++) {
matrixa[i][j] = Integer.parseInt(line[counter]);
counter++;
System.out.print(matrixa[i][j] + " ");
}
System.out.println();
} }catch (Exception e) {}

Leaving a ticker variable at when your lines is equal to "#"
int ticker;
for(int i = 0; i < lines.length; i++){
if(lines[i].equals("#")) ticker = i;
}
This ticker then can be used to break the array. This could also be used earlier to break up the array into 2 separate arrays if that is expected.
String currentLine;
String[] line = new String[15];
String[] line2 = new String[15];
int i = 0;
while(line != null && !currentLine.equals("#")){
line = MyReader.readLine().split("");
currentLine = line[i];
if(currentLine.equals("#")) line[i] = null;
i++;
}
while(line2 != null)){
line2 = MyReader.readLine().split("");
}
They can be parsed into matrices and then math can be done on them from there.
Best of luck with your endeavors.

Related

Read the data from the file and store it in two arrays

hello I am having trouble with trying to read a file and take the two columns of the file and put them respectively in their own arrays. Any help would be appreciated! Thanks!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.println("Please enter the name of the file to be read");
String fileName = keyboard.nextLine();
Scanner chirping = null;//user input for file name
boolean fileValue = false; //this makes the value false until the correct file name is inputed
while(!fileValue) {
try {
FileReader dates = new FileReader(fileName); // connects to the user inputted file
chirping = new Scanner(dates); //scans the file
fileValue = true; //turns file value to true which takes us out of the while loop
}//end try
catch(IOException e) {
System.out.println("File Not Found, Please Try Again: ");
fileName = keyboard.nextLine();
}//end catch
}// end while
double[] dataSet = new double[30];
double[] chirpFreq = new double[30];
double[] temp = new double[30];
//double[] temp = new double[chirping.nextInt()];
for(int i = 0; chirping.hasNextDouble(); i++) {
dataSet[i] = chirping.nextDouble();
}
for(int j = 0; j <= dataSet.length; j++) {
if(j%2 == 0) {
chirpFreq[j] = dataSet[j];
}
else {
temp[j] = dataSet[j];
}
}
for(int i = 0; i <= chirpFreq.length; i++) {
System.out.print(chirpFreq[i]+ " ");
}
chirping.close();
}
//These are the values i am trying to sort into two separate arrays
20 88.6
16 71.6
19.8 93.3
18.4 84.3
17.1 80.6
15.5 75.2
14.7 69.7
17.1 82
15.4 69.4
16.2 83.3
15 79.6
17.2 82.6
16 80.6
17 83.5
14.4 76.3
I don't usually use nextDouble() to read files so i don't know what your problem is exactly, but you can refactor your code to this:
double[] firstColumn = new double[30];
double[] secondColumn = new double[30];
String line = "";
int i = 0;
// keep reading until there is nothing to read
while( (line = chirping.nextLine()) != null ) {
// this is a regex that splits the line into an array based on whitespace
// just use " " if your data is separated by space or "\t" if tab
String[] columns = line.split("\\s+");
firstColumn[i] = Double.parseDouble(columns[0]);
secondColumn[i++] = Double.parseDouble(columns[1]);
}
chirping.close();

Why can't I access my 2D array outside of the loop?

I'm having some trouble accessing my 2D array (myArray) outside of this the loop. I want to access it using other methods, but I can't even access it in this method. It prints out correctly as it's looping, but the test print of
System.out.println(myArray[10][2]);
is always null. So it's like the array isn't actually filling or something. Anyone know what I'm doing wrong here?
package titanic;
import java.io.*;
import java.util.*;
public class Titanic {
public static final int ROW = 1309;
public static final int COLUMN = 6;
public static String [][] myArray = new String[ROW][COLUMN];
public static String[][] arraySetup(){
int recordCounter = 0;
String[][] myArray = new String[ROW][COLUMN];
String[] name = new String [ROW];
try {
BufferedReader br = new BufferedReader(new FileReader("C:/Users/Tom/Desktop/Titanic.txt"));
String line;
for (int i = 0; i < 1309; i++){
while((line = br.readLine()) != null){
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(myArray[10][2]);
System.out.println(recordCounter + " records.");
return myArray;
}
As you have you while loop inside for loop that is used to for indexing your output array while loop always writes into the myArray[0][0] to myArray[0][5]
for (int i = 0; i < 1309; i++){ // i is 0
while((line = br.readLine()) != null){ // you go through all the lines while i is 0
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
Because of that your check always returns null.
System.out.println(myArray[10][2]);
I think the problem in your code is right there
for (int i = 0; i < 1309; i++){ // you loop 1308 time
while((line = br.readLine()) != null){ /* in each loop, you loop
until you have read all the file so you read 1308 time the file. But when
you reach the end of file on the first iterration, it wont read the file on the 1307
other iterration and all data will be store in myArray[0][0-5]*/
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
Don't use for and while loop together. During the first for loop, your while reads all file contents and all other array positions remain empty.
Try this instead:
int i=0;
while ((line = br.readLine()) != null){
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
...
myArray[i][5] = tmp[5];
i++;
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}

store 1d array from text file java

Am I reading the following input correctly?
Here is my code so far:
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
String[] parts = line.split(",");
for (int i = 0; i< parts.length; i++) {
rangeNo[i]= Integer.parseInt(parts[i]);
System.out.println("{" + rangeNo[i] + "}");
}
}
and this is my input
[2,9], [3,11]
Also, when I try to print the value of rangeNo[3] it return 0 instead of 3
can someone help me out with this?
Do you expect [2,9], [3,11] to be in one line or two separate lines?
If its supposed to be one line then you might want to try something like this
Integer rangeNo[] = new Integer[10];
String line = "[2,9], [3,11]";
line = line.replace('[', ' ');
line = line.replace(']', ' ');
String[] parts = line.split(",");
for (int i = 0; i < parts.length; i++) {
rangeNo[i] = Integer.parseInt(parts[i].trim());
System.out.println("{" + rangeNo[i] + "}");
}
when you check here
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
it's matching first condition. i.e works fine for [2,9] not after that thus only 2 and 9 are getting stored here.
String[] parts = line.split(",");
so
parts[0]=2
parts[1]=9
parts[2]=0

Array of Arrays to table

Faced problem of printing Array of Arrays to table. My program saves table data to separate text files (separate file for each day). Now I want to Read it all and sum each fields.
My saved text files looks like:
0 Name auto note note.tot insurance ins.tot offer
1 john 51 6 2 21 44 12
2 peter 32 5 1 36 65 20
3 smith 12 2 1 45 53 9
4 mike 5 0 0 17 55 11
I have manged a way to read it and save number values to arrays[][]. But now I need to print that arrays to table.
Here is my Read from files code:
OK4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File f = new File(fileName);
if (f.exists()) {
try {
tableModel = new DefaultTableModel(new Object[] {"#", "Name", "auto", "note", "note.tot", "insurance", "ins.tot", "offer"},0);
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] colHeaders = line.split("\\s+");
tableModel.setColumnIdentifiers(colHeaders);
while ((line = br.readLine()) != null) {
String[] data = line.split("\\s+");
tableModel.addRow(data);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "This date was not saved");
};
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
}
});
And here is a code I am getting problems with:
OK5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int[][] array = null;
int counter = 0;
mon = (String) month.getValue();
for (int i = 1; i < 32; i++) {
counter = 0;
fileName= mon + i + ".txt";
File f = new File(fileName);
if (f.exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] colHeaders = line.split("\\s+");
tableModel = new DefaultTableModel(new Object[] {"#", "name", "auto", "note", "note.tot", "insurance", "ins.tot", "offer"}, 0);
tableModel.setColumnIdentifiers(colHeaders);
while ((line = br.readLine()) != null) {
counter = counter + 1;
String[] info = line.split("\\s+");
for(int j = 2; j < 8; j++) {
int num = Integer.parseInt(info[j]);
array[j][counter]=array[j][counter] + num;
}
};
} catch (Exception ex) {}
};
};
// and here is trying to display it. but it wont work
tableModel.addRow(array[1][]);
}
});
error code is:
int cannot be converted to vector
But should I convert it to vector? may be there is another way to display it in table?
Actually the errorcode is completely senseless, since the actual error is simply the access of the matrix: tableModel.addRow(array[1][]); should actually result in a syntax-error for the second brackets ([]). To fix the syntax error replace the line with tableModel.addRow(array[1]);. And a general note: please format your code, it is completely unreadable.

How do I read each column of a txt file, and place them in separate arrays?

I'm doing a Programming Assignment and basically I need to read from a txt file and sort everything in there in different arrays allowing me to display everything in the cmd prompt neatly and be able to delete stuff.
h Vito 123
d Michael 234 Heart
s Vincent 345 Brain Y
n Sonny 456 6
a Luca 567 Business
r Tom 678 Talking Y
j Anthony 789 Maintenance N
d Nicos 891 Bone
n Vicky 911 7
First column needs to be the employeeRole (employee, doctor). The second column being the employeeName. Third column being the employeeNumber and some of them have have a fourth column (if it's a number it's number of patients. Y is for like sweeping, or answering calls)
So my thought process was put each column into it's own array and then writing it out that way. I was able to put each row into its own array with
public class ReadingFile {
// String test;
// char[] employeeRole = new char[9];
String[] employeeRole = new String[9];
String[] employeeName = new String[9], specialty;
String[] wholeLine = new String[9];
// String word;
int[] employeeNum = new int[9];
int r, n, l, num;
public void Reader()
{
Scanner inputStream = null;
Scanner inputStream2 = null;
Scanner inputStream4 = null;
try
{
BufferedReader inputStream3 =
new BufferedReader(new FileReader("data.txt"));
inputStream = new Scanner(new FileInputStream("data.txt"));
inputStream =
new Scanner(new FileInputStream("data.txt"));
inputStream2 =
new Scanner(new FileInputStream("data.txt"));
inputStream4 =
new Scanner(new FileInputStream("data.txt"));
System.out.println("Yeah");
}
catch(FileNotFoundException e){
System.out.println("File Not found");
System.exit(1);
}
for (l=0; l<9; l++)
{
wholeLine[l] = inputStream2.nextLine();
System.out.println(wholeLine[l]);
}
But I couldn't figure out what to do from there. Doing a split would then put an array into an array? Which means I would put each line into an array and then each word into an array?
So I tried something else, anything with the length not equal to 1 would be the employeeNum, but then they there were the N's and Y's and the number of pateints.
for(r=0; r<9; r++) //role
{
String next = inputStream4.next();
while( next.length() != 1)
{
next = inputStream4.next();
}
employeeRole[r] = next;
System.out.println(employeeRole[r]);
}
I also tried
for (r=0; r<9; r++)
{
employeeRole[r] = wholeLine[r].substring(wholeLine[r].indexOf(1));
//inputStream.nextLine();
System.out.println(employeeRole[r]);
}
I'm just not sure if I'm going the right way about it? If I'm making it more difficult than it really is? Or if there's an easier way to do this. But after everything is done, the output should be able to basically say
Doctors: 2
Name: Michael Employee Number: 234 Specialty: Heart
Name: Nicos Employee Number: 891 Specialty: Bone
Any help would be greatly appreciated, thanks!
You don't have to open 4 streams in order to read the file (I guess you wanted to open "one per column" but you shouldn't do it).
Second, you can split the string on spaces (" ") which will provide you the columns (for every line separately) exactly like you want.
Code example:
BufferedReader br = null;
String[] characters = new String[1024];//just an example - you have to initialize it to be big enough to hold all the lines!
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("data.txt"));
int i=0;
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split(" ");
//for the first line it'll print
System.out.println("arr[0] = " + arr[0]); // h
System.out.println("arr[1] = " + arr[1]); // Vito
System.out.println("arr[2] = " + arr[2]); // 123
if(arr.length == 4){
System.out.println("arr[3] = " + arr[3]);
}
//Now if you want to enter them into separate arrays
characters[i] = arr[0];
// and you can do the same with
// names[1] = arr[1]
//etc
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Categories