Creating an array from a matrix input - java

I have an input file which is in the form of a matrix:
I want to turn this input from a file into an array. I am not sure how to go about it.Any suggestions? I've tried the code below but when I compile the code and pass the file as an input I am returned with nothing.
public static void main(String[]args)
{
int size;
Scanner entry = new Scanner(System.in);
int myMatrix[][] = new int[0][0];
try
{
size = entry.nextInt();
myMatrix = new int[size][size];
for (int i=0; i<size; i++)
{
for (int j = 0; j<size; j++)
{
myMatrix[i][j] = entry.nextInt();
}
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++)
System.out.print(myMatrix[i][j] + " ");
System.out.println();
}
}
catch (Exception e)
{
}
finally
{
entry.close();
}

Change (System.in) to: (new File("filename.txt"))
Here's more info on reading from text files:
https://www.w3schools.com/java/java_files_read.asp

You can use Files.lines to read all the lines from a file.
String filePath = entry.nextLine();
int[][] myMatrix = Files.lines(Paths.get(filePath))
.map(l -> Arrays.stream(l.split(" ")).mapToInt(Integer::parseInt).toArray())
.toArray(int[][]::new);

Related

How can I take the length from the text files in java?

I am new in java. Firstly, I'm sorry for my English. I wrote a code to merge two different txt files in the mergedFile.txt with determined data from the data1.txt and data2.txt. I create 5 different arrays to use them better but I cannot learn the length of words in the textfiles so arrays are using determined parameter. If I want to add another student, this codes don't work. Can you help me?
data1.txt
ID,Name,LastName,Department
12345,John,Samon,Computer Science
14524,David,Souza,Electric and Electronic
.
.
data2.txt
ID,Q1,Q2,Q3,Midterm,Final
12345,100,90,75,89,100
14524,80,70,65,15,90
.
margedFile.txt
ID,Name,Q_Average,Midterm,Final,Department
12345,John,88.3,89,100,Computer Science
14524,David,67.0,100,70,Electric and Electronic
This is ReadData Class
import java.io.FileInputStream;//import java.io library
import java.util.Scanner;//import scanner library
public class ReadData {
public static String[] Read(String filename,String filename2) {
Scanner scan = null;
Scanner scan1 = null;/
FileInputStream input1 = null;
FileInputStream input = null;
String[] result = new String[3];
try {
input = new FileInputStream(filename);
scan = new Scanner(input);
input1 = new FileInputStream(filename2);
scan1 = new Scanner(input1);
String[][] myArray = new String[4][4];
String[][] myArray1 = new String[4][6];
while(scan.hasNext() || scan1.hasNext()) {
for (int i = 0; i < myArray.length; i++) {
String[] split =
scan.nextLine().trim().split(",");
for (int j = 0; j < split.length; j++)
{
myArray[i][j] = split[j];
}
}
for (int i = 0; i < myArray1.length; i++) {
String[] split1 = scan1.nextLine().trim().split(",");
for (int j = 0; j < split1.length; j++) {
myArray1[i][j] = split1[j];
}
}
}
int[][] quiz = new int[3][3];
double[] average = new double[3];
int sum = 0;
double averagee = 0;
for (int i = 0; i < quiz.length; i++) {
for (int j = 0; j < quiz.length; j++) {
quiz[i][j] = Integer.parseInt(myArray1[i+1][j+1]);
sum += quiz[i][j];
}
averagee = sum/quiz.length;
average[i] = averagee;
sum = 0;
}
for (int i = 1; i < myArray1.length; i++) {
for (int j = 1; j < myArray1.length; j++) {
if(myArray[i][0].equalsIgnoreCase(myArray1[j][0])) {
result[i-1] = "\n" + myArray[i][0] + " "+ myArray[i][1] + " " + (average[j-1]) +" "+ myArray1[j][4] +" " + myArray1[j][5] + " "+ myArray[i][3];
//System.out.println(Arrays.deepToString(myArray[i]) + " " + Arrays.deepToString(myArray1[j]));
}
}
}
//System.out.println(Arrays.deepToString(quiz));
//System.out.println(Arrays.toString(average));
}
catch(Exception e) {
System.out.println(e);
}
return result;
}
}
This is WriteData class
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class WriteData extends ReadData {
void Write(String filename) {
PrintWriter writer = null;
FileOutputStream output = null;
try {
output = new FileOutputStream(filename);
writer = new PrintWriter(output);
writer.print("ID,Name,Q_Average,Midterm,Final,Department ");
writer.print(Arrays.toString(Read("data1.txt",
"data2.txt")));
writer.flush();
writer.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}

Java- How to compare 1D array with 2D array

I have trouble compare 1D array with 2D array. I already import the txt file to 1D array and 2D array. The 1D array contains 20 correct answer (True and False). The 2D array contains 2000 student answers (100 students * 20 answers per student).
I want to design a program that shows the score for each student, which I already tried to program. Can you help me to figure out which part I did wrong?
The second part of the program is to print out for each question, how many student got right for each question?
Thank you so much!!
import java.io.*;
import java.util.Arrays;
public class Scores
{
public static void main(String[] args) {
try {
File AnswerFile = new File("/Users/shaovera/NetBeansProjects/Scores/QuestionAnswer.txt");
FileReader AnswerReader = new FileReader(AnswerFile);
BufferedReader answerreader = new BufferedReader(AnswerReader);
String[] words = new String[20];
for(int a = 0; a < words.length; a++) {
words[a] = answerreader.readLine();
System.out.println(words[a]);
}
answerreader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
try {
File StudentFile = new File("/Users/shaovera/NetBeansProjects/Scores/StudentAnswer.txt");
FileReader StudentReader = new FileReader(StudentFile);
BufferedReader studentreader = new BufferedReader(StudentReader);
String[][] table = new String[100][20];
for (int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
table[i][j] = studentreader.readLine();
System.out.print(table[i][j] + " ");
}
System.out.println("");
}
studentreader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
int count=0;
int student=0;
String[] words = new String[20];
String[][] table = new String[100][20];
for (int column = 0; column < words.length; column++) {
for (int row = 0; row < 100; row++) {
if (words[row] == table[row][column]) {
count++;
student++;
System.out.print("student#" + student + ":" + count);
}
}
}
}
I think this correct code (I wrote comment in line when you have problems)
public static void main(String[] args){
String[]words= new String[20]; // before load from file
String[][]table =new String[100][20]; // before load from file
try{
File AnswerFile=new File("/Users/shaovera/NetBeansProjects/Scores/QuestionAnswer.txt");
FileReader AnswerReader = new FileReader(AnswerFile);
BufferedReader answerreader = new BufferedReader(AnswerReader);
for(int a=0; a<words.length;a++){
words[a]=answerreader.readLine();
System.out.println(words[a]);
}
answerreader.close();
}
catch (Exception ex){
ex.printStackTrace();
}
try{
File StudentFile=new File("/Users/shaovera/NetBeansProjects/Scores/StudentAnswer.txt");
FileReader StudentReader = new FileReader(StudentFile);
BufferedReader studentreader = new BufferedReader(StudentReader);
for (int i = 0; i <table.length; i++) {
for(int j=0;j < table[i].length; j++){
table[i][j]= studentreader.readLine();
System.out.print(table[i][j]+" ");
}
System.out.println("");
}
studentreader.close();
}
catch (Exception ex){
ex.printStackTrace();
}
for (int column = 0; column < words.length; column++) {
int student = 0;
for (int row = 0; row < table.length; row++) {
if (Objects.equals(words[column],table[row][column])) {
student++;
}
}
System.out.println("student#" + student + ":" + column);
}
}

Java read file and write into array

--------------- SOLVED !!! -----------------------
I would like to thank you, everyone, for your help !
I have to read a file where I have nxm elements, and then put those elements into 2D array, and then print it out. I'm a little bit stuck at printing my array out. In file.txt I have 2x2 => 2 lines and 2 columns, and elements are:1 2 3 4.
Here is my code:
public class ex_1
{
public static void main(String args[])
{
FileReader fr = new FileReader("FirstMatrix.txt");
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
String[] split = s.split("x");
int k=Integer.parseInt(split[0]);
int l=Integer.parseInt(split[1]);
System.out.println("Matrix dimensions: "+k+" lines, "+l+" columns si "+k*l+" elements");
System.out.print("Elements in matrix are: \n");
int[][] FirstMatrix = new int [k][l];
while ((s = br.readLine()) != null)
{
for(int i=0; i<FirstMatrix.length; i++)
for(int j=0; j<FirstMatrix[i].length;j++)
{
FirstMatrix[i][j] = Integer.parseInt(s);
System.out.println("FirstMatrix["+i+"]["+j+"]="+FirstMatrix[i][j]);
}
}
br.close();
My output, how it is:
FirstMatrix[0][0]=1
FirstMatrix[0][1]=1
FirstMatrix[1][0]=1
FirstMatrix[1][1]=1
FirstMatrix[0][0]=2
FirstMatrix[0][1]=2
FirstMatrix[1][0]=2
FirstMatrix[1][1]=2
FirstMatrix[0][0]=3
FirstMatrix[0][1]=3
FirstMatrix[1][0]=3
FirstMatrix[1][1]=3
FirstMatrix[0][0]=4
FirstMatrix[0][1]=4
FirstMatrix[1][0]=4
FirstMatrix[1][1]=4
How I want it to be:
FirstMatrix[0][0]=1
FirstMatrix[0][1]=2
FirstMatrix[1][0]=3
FirstMatrix[1][1]=4
Does anyone know how I can fix this print out please?
EDIT!!
If I change code like this
int[][] FirstMatrix = new int [k][l];
while ((s = br.readLine()) != null)
{
for(int i=0; i<k;i++)
for(int j=0; j<l; j++)
{
FirstMatrix[i][j] = Integer.parseInt(s);
}
}
br.close();
for(int i=0; i<FirstMatrix.length; i++)
for(int j=0; j<FirstMatrix[i].length;j++)
{
System.out.println("FirstMatrix["+i+"]["+j+"]="+FirstMatrix[i][j]);
}
I get this output:
FirstMatrix[0][0]=4
FirstMatrix[0][1]=4
FirstMatrix[1][0]=4
FirstMatrix[1][1]=4
You're doing n*n times the loop. Because everytime that you read the file are entering the loop. If you know that every line is a number, you could read only one time and print each row.
Try it and let me know what happen.
Best regards from Mexico
After this line System.out.print("Elements in matrix are: \n");
paste this code.
int[][] FirstMatrix = new int [l][k];
for(int j=0; j<l;j++)
{
for(int i=0; i<k; i++) {
s = br.readLine());
FirstMatrix[j][i] = Integer.parseInt(s);
System.out.println("FirstMatrix["+j+"]["+i+"]="+FirstMatrix[j][i]);
}
}
Don't use while loop.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ex_1 {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("FirstMatrix.txt");
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
String[] split = s.split("x");
int k = Integer.parseInt(split[0]);
int l = Integer.parseInt(split[1]);
System.out.println("Matrix dimensions: " + k + " lines, " + l + " columns si " + k * l + " elements");
System.out.print("Elements in matrix are: \n");
int[][] FirstMatrix = new int[k][l];
for (int lineIndex = 0; lineIndex < k; lineIndex++) {
for (int columnIndex = 0; columnIndex < l; columnIndex++) {
s = br.readLine();
FirstMatrix[lineIndex][columnIndex] = Integer.valueOf(s);
}
}
for (int a = 0; a < k; a++) {
for (int b = 0; b < l; b++)
System.out.print(FirstMatrix[a][b] + " ");
System.out.println();
}
br.close();
}
}

How to print in file array

Soo, I have to insert list of arrays into a specific text document.
The array list is inset by user at case 1 and it works well.
When I try call case 4 without any data, the file is created and also it's empty.
When I do this with an array list I get the Error message from catch.
How can I fix it?
Here is the call to function.
case 4: System.out.println("\nLungimea dintre doua orase alaturate\n");
try{
System.out.println("oabdobasoda");
salvareOras();
}catch (Exception e){
System.out.println("Eroare");
}
and here is the function.
public static void salvareOras()
{
for(int i = 0; i<drum.size()-1; i++){
for(int j = 0; i<drum.size(); j++){
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}
try {
FileOutputStream fOut = new FileOutputStream("distante.txt");
PrintStream ps = new PrintStream(fOut);
for(int i = 0; i <drum.size()-1; i++){
ps.println("d(" + drum.get(i).getNume()+","+drum.get(i+1).getNume()+")="+distOras(drum.get(i), drum.get(i+1)));
}
ps.close();
fOut.close();
} catch(IOException ex){
System.out.println("Nu s-a putut crea fisierul");
System.exit(1);
}
}
You made a minor mistake in your 2nd for loop:
for(int i = 0; i<drum.size()-1; i++){
//specifically on this line here:
for(int j = 0; i<drum.size(); j++){
//^//That is not j
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
//that means ^ will throw an IndexOutOfBoundsException
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}
Just change it to:
for(int i = 0; i<drum.size()-1; i++){
for(int j = 0; j<drum.size(); j++){
//^ j
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}

Printing ListArrays to a txt file

I have a method that is suppose to take 3 arrays and save them to a txt file. But it doesnt print to the list. Here is my code for the method
public static void saveAndExit(int count, String[] makeArray, String[] moduleArray, double [] msrpArray) throws IOException{
File carList = new File("cars_list.txt");
PrintWriter pw = new PrintWriter(carList);
int index = 0;
String[] finalMSRPArray = new String[12];
for (int i = 0; i < msrpArray.length; i++){
finalMSRPArray[i] = String.valueOf(msrpArray[i]);
}
while(count < makeArray.length && count < moduleArray.length && count < msrpArray.length){
pw.write(makeArray[index]+"\n");
pw.write(moduleArray[index]+"\n");
pw.write(finalMSRPArray[index]+"\n");
index++;
}
pw.close();
}
Any help is much appreciated!

Categories