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

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

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 - text to 2d array remove spaces"

have the text file containing a 2d array with a fixed row and column [6][3]
a 5 7
b 9 7
c 1 0
d 0 5
e 8 7
f 0 4
i need to put the data into array playerOne[][]
This is my code
try {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNextLine()) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
String line = sc.next().trim();
if (line.length() > 0) {
playerOne[i][j] = line;
System.out.println(i+ " " +j+ " "+ line);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(Arrays.toString(playerOne));
}
i get an NoSuchElementException error, and it cannot print the array
instead of using nextLine use .next directly
.next will get the next value regardless to the next value line
try {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNext()) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
String nextValue= sc.next().trim();
playerOne[i][j] = nextValue;
System.out.println(i+ " " +j+ " "+ nextValue);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(Arrays.toString(playerOne));
}

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

Reading contents from a text file and storing them into an array

I have a text document that contains a 5x5 table with these values
5 5
39 95 99 56 41
88 8 1 48 75
3 58 13 54 80
92 72 74 25 86
30 38 3 21 2
I have to add them into an array, and display the lowest value(which is 1) and tell the location of the lowest value(row 1 column 2).
public static void main(String[] args)
{
Scanner input;
File fileIn = new File("src/array2d/array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
int[][] array = new int[5][5];
for(int row = 0;row<array.length;row++) {int[] column = array[row];
{
for(int columnIndex = 0; columnIndex<column.length; columnIndex++);
}
}
try
{
input = new Scanner(fileIn);
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
}
This code actually stores your input into an array.
public static void main(String[] args) {
Scanner input;
File fileIn = new File("src/array2d/array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
int[][] array = new int[5][5];
try
{
input = new Scanner(fileIn);
String values = input.nextLine();
String[] value = values.split("\\s+");
int index = 0;
for(int row = 0;row < 5;row++)
{ index = row;
for(int col = 0 ; col < 5; col++){
array[row][col] = Integer.parseInt(value[index*5 + col]);
}
}
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
Using answer from #vikasn91, I edited it a bit to correctly assign the values to array, find the lowest number and its location in the array:
try {
input = new Scanner(fileIn);
int lowestCol = 0;
int lowestRow = 0;
int lowest = 0;
for (int row = 0; row < 5; row++) {
String values = input.nextLine();
String[] value = values.split("\\s+");
for (int col = 0; col < 5; col++) {
array[row][col] = Integer.parseInt(value[col]);
if (row == 0 && col == 0) {
lowest = array[row][col];
} else if (array[row][col] < lowest) {
lowestCol = col;
lowestRow = row;
lowest = array[lowestRow][lowestCol];
}
}
}
System.out.println("Lowest number: " + lowest);
System.out.println("Found in row: " + lowestRow + ", col: " + lowestCol);
} catch (FileNotFoundException e) {
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
public static void main(String[] args)
{
Scanner input;
File fileIn = new File("array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
try
{
input = new Scanner(fileIn);
int row = input.nextInt();
int column = input.nextInt();
int min = Integer.MAX_VALUE;
int val;
int minR=0,minC=0;
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
val = input.nextInt();
if(val<min){
min = val;
minR = i;
minC = j;
}
}
}
System.out.println("Min Value is " + min + "\nat position (" + minR + "," + minC + ")" );
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
If you're using the Scanner, you don't need to split or parse integers directly. The default delimiter is space.
Scanner s = new Scanner(new FileReader("src/array2d/array2dtest1.txt"));
int numRows = s.nextInt();
int numCols = s.nextInt();
int[][] array = new int[numRows][numCols];
int least = Integer.MAX_VALUE;
int leastRow = -1;
int leastCol = -1;
for(int r = 0; r < numRows; r++) {
for(int c = 0; c < numCols; c++) {
if((array[r][c] = s.nextInt()) < least) {
leastRow = r;
leastCol = c;
}
}
}

Categories