Java read file and write into array - java

--------------- 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();
}
}

Related

Creating an array from a matrix input

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);

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);
}
}

How to determine how big is the treasure map (rows and columns) from a textfile?

I'd like to know how to figure out the rows and columns of a passed textfile.
Suppose the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
This textfile has 10 rows and 20 columns and I'm facing troubles with how to get those rows and columns for my constructor (DONT WORRY ABOUT "X" symbols). I just would like to know how to get rows and columns from the textfile/ would like to know how to figure out how big the map is.
I need help with the second constructor in the code:
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
public TreasureMap(String fileName) throws Exception{
Scanner data = new Scanner(new File(fileName));
int counter = 0;
while(data.hasNextLine())
{
counter++;
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}
Here's some code you can use to read lines from a file:
File file = new File(fileName);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
int rows = 0;
int cols = 0;
while ((line = br.readLine()) != null) {
// process the line
rows++;
cols = line.length(); // always the size of the last line in the file
}
}
br.close();
Based on your implementation, this would give you width and height of your input file.
public TreasureMap(String fileName) throws Exception{
Scanner data = new Scanner(new File(fileName));
int width = 0;
int height = 0;
while(data.hasNextLine())
{
String line = data.nextLine();
width = Math.max(width, line.length());
height++;
}
System.out.println(width + " x " + height);
}

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