How can I take the length from the text files in java? - 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
}
}
}

Related

Accuracy of Multi Layer Neural Network using Backpropagation around 86% normal?

Recently, I started trying to train a neural network using backpropagation. The network structure is 784-512-10, and I used the Sigmoid activation function. When I tested a single-layer network on the MNIST dataset, I got around 90%. My results are around 86% with this multi-layer network, is this normal? Did I get the backpropagation part wrong?
Here is my code:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class NeuralNetwork{
public static double learningRate = 0.01;
public static int epoch = 15;
public static int ROWS = 28;
public static int COLUMNS = 28;
public static int INPUT = ROWS * COLUMNS;
public static int outNum = 10;
public static int hiddenNum = 512;
public static double[][] weights2 = new double[outNum][hiddenNum];
public static double[] bias2 = new double[outNum];
public static double[][] weights1 = new double[hiddenNum][INPUT];
public static double[] bias1 = new double[outNum];
private static final double TRAININGSIZE = 10;
public static double[][] inputs = new double[outNum][INPUT];
private static final double[][] target = new double[outNum][outNum];
private static final ArrayList<String> filenames = new ArrayList<>();
private static final ArrayList<Integer> yetDone = new ArrayList<>();
public static double[] actual = new double[outNum];
public static Random rand = new SecureRandom();
public static Scanner input = new Scanner(System.in);
public static void main(String[]args) throws Exception {
System.out.println("1. Learn the network");
System.out.println("2. Guess a number");
System.out.println("3. Guess file");
System.out.println("4. Guess All Numbers");
System.out.println("5. Guess image");
switch (input.nextInt()){
case 1:
learn();
break;
case 2:
guess();
break;
case 3:
guessFile();
break;
case 4:
guessAll();
break;
}
}
public static void guessAll() throws IOException, ClassNotFoundException {
System.out.println("Recognizing...");
/*
for(int x = 1; x < 60000; x++){
filenames.add("data/" + String.format("%05d",x) + ".txt");
}
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
Layers lay = (Layers) ois.readObject();
int correct = 0;
for (String z : filenames) {
double[] a = scan(z,0);
correct += getBestGuess(sigmoid(lay.step(a))) == actual[0] ? 1 : 0;
}
System.out.println("Training: " + correct + " / " + filenames.size() + " correct.");
filenames.clear();
*/
for(int x = 60000; x < 70000; x++){
filenames.add("data/" + String.format("%05d",x) + ".txt");
}
ObjectInputStream oiss = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network1.ser")));
Layers lays1 = (Layers) oiss.readObject();
ObjectInputStream oiss2 = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network2.ser")));
Layers lays2 = (Layers) oiss2.readObject();
int corrects = 0;
for (String z : filenames) {
double[] a = scan(z,0);
corrects += getBestGuess(sigmoid(lays2.step(sigmoid(lays1.step(a))))) == actual[0] ? 1 : 0;
}
System.out.println("Testing: " + corrects + " / " + filenames.size() + " correct.");
System.out.println("Done!");
}
public static void makeList(){
for(int index = 0; index < TRAININGSIZE; index++){
int indices = rand.nextInt(yetDone.size() - 1) + 1;
filenames.add("data/" + String.format("%05d",yetDone.get(indices)) + ".txt");
yetDone.remove(indices);
}
prepareData();
for(int indices = 0; indices < outNum; indices++) {
for(int index = 0; index < outNum; index++){
target[indices][index] = 0;
}
target[indices][(int)actual[indices]] = 1;
}
}
public static void prepareData(){
for(int index = 0; index < outNum; index++){
try {
inputs[index] = scan(filenames.get(index), index);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
public static double[] scan(String filename, int index) throws FileNotFoundException {
Scanner in = new Scanner(new File(filename));
double[] a = new double[INPUT];
for(int i = 0; i < INPUT; i++){
a[i] = in.nextDouble() / 255;
}
actual[index] = in.nextDouble();
return a;
}
public static void guessFile() throws IOException, ClassNotFoundException {
System.out.print("Enter Filename: ");
double[] a = scan(input.next(), 0);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
Layers lay = (Layers) ois.readObject();
double[] results = lay.step(a);
System.out.println("This is a " + getBestGuess(sigmoid(results)) + "!");
System.out.println(Arrays.toString(results));
}
public static double guess(double[] a) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
Layers lay = (Layers) ois.readObject();
double[] results = lay.step(a);
return getBestGuess(sigmoid(results));
}
public static void guess() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
System.out.println("Input number: ");
Layers lay = (Layers) ois.readObject();
double[] a = new double[INPUT];
for(int index = 0; index < a.length; index++){
a[index] = input.nextInt();
}
double[] results = lay.step(a);
System.out.println("This is a " + getBestGuess(sigmoid(results)) + "!");
System.out.println(Arrays.toString(sigmoid(results)));
}
public static void learn() {
System.out.println("Learning...");
initialise(weights2, outNum, hiddenNum);
initialise(bias2);
initialise(weights1,hiddenNum, INPUT);
initialise(bias1);
Layers lay2 = new Layers(weights2, bias2, outNum, hiddenNum);
Layers lay1 = new Layers(weights1, bias1, hiddenNum, INPUT);
double[] result2 = new double[lay2.outNum];
double[] result1 = new double[lay1.outNum];
double[] a2;
double[] a1;
double cost = 0;
double sumFinal;
for(int x = 0; x < epoch; x++) {
yetDone.clear();
for(int y = 0; y < 60000; y++){
yetDone.add(y);
}
for (int ind = 0; ind < 200; ind++) {
filenames.clear();
makeList();
for (int n = 0; n < lay2.outNum; n++) {
a1 = inputs[n]; //number
result1 = sigmoid(lay1.step(a1));
a2 = result1;
result2 = sigmoid(lay2.step(a2));
for (int i = 0; i < lay2.outNum; i++) {
for (int j = 0; j < lay2.INPUT; j++) {
weights2[i][j] += learningRate * a2[j] * (target[n][i] - result2[i]);
cost += Math.pow((target[n][i] - result2[i]), 2);
}
}
for(int i = 0; i < lay1.outNum; i++){
for(int j = 0; j < lay1.INPUT; j++){
sumFinal = 0;
for(int k = 0; k < lay2.outNum; k++){
// weight * derivSigma(outputHiddenLayer) * 2(out - expected)
sumFinal += result1[k] * (1 - result1[k]) * 2 * (result2[k] - target[n][k]); // * weights2[k][i]
}
weights1[i][j] -= learningRate * a1[j] * sumFinal * result1[i] * (1 - result1[i]);
}
}
}
lay1.update(weights1, bias1);
lay2.update(weights2, bias2);
}
System.out.println("Epoch " + x + ": " + cost);
cost = 0;
}
System.out.println(Arrays.toString(result1));
System.out.println(Arrays.toString(result2));
for(double[] arr : inputs) {
System.out.println("This is a " + getBestGuess(sigmoid(lay2.step(sigmoid(lay1.step(arr))))) + "!");
}
try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("network1.ser")))) {
oos.writeObject(lay1);
} catch (IOException ex) {
ex.printStackTrace();
}
try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("network2.ser")))) {
oos.writeObject(lay2);
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("Done! Saved to file.");
}
public static double sigmoid(double x){
return 1 / (1 + Math.exp(-x));
}
public static double[] sigmoid(double[] weights){
for(int index = 0; index < weights.length; index++){
weights[index] = sigmoid(weights[index]);
}
return weights;
}
public static void initialise(double[] bias){
Random random = new Random();
for(int index = 0; index < bias.length; index++){
bias[index] = random.nextGaussian();
}
}
public static void initialise(double[][] weights, int outNum, int INPUT){
Random random = new Random();
for(int index = 0; index < outNum; index++){
for(int indice = 0; indice < INPUT; indice++){
weights[index][indice] = random.nextGaussian();
}
}
}
public static int getBestGuess(double[] result){
double k = Integer.MIN_VALUE;
double index = 0;
int current = 0;
for(double a : result){
if(k < a){
k = a;
index = current;
}
current++;
}
return (int)index;
}
}
class Layers implements Serializable {
private static final long serialVersionUID = 8L;
double[][] weights;
double[] bias;
int outNum;
int INPUT;
public Layers(double[][] weights, double[] bias, int outNum, int INPUT){
this.weights = weights;
this.bias = bias;
this.outNum = outNum;
this.INPUT = INPUT;
}
public void update(double[][] weights, double[] bias){
this.weights = weights;
this.bias = bias;
}
public double[] step(double[] aa){
double[] out = new double[outNum];
for (int index = 0; index < outNum; index++) {
for (int indices = 0; indices < INPUT; indices++) {
out[index] += weights[index][indices] * aa[indices];
}
}
return out;
}
}
Thanks in advance!

how to give chance to all clients one by one to send a number and block a client to send number if its not his chance in socket programming in java

Multiple clients and one server for bingo game
Server.java
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.ArrayList;
public class Server {
int[][] card = new int[5][5];
int[][] bingo = new int[5][5];
public int[][] bingoCard() {
ArrayList<Integer> alreadyUsed = new ArrayList<>();
boolean valid = false;
int tmp = 0;
for (int i = 0; i <= 4; i++) {
for (int row = 0; row < card.length; row++) {
while (!valid) {
tmp = (int) (Math.random() * 25) + 1;
if (!alreadyUsed.contains(tmp)) {
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
bingo[row][i] = tmp;
valid = false;
}
}
//create array to make title.
String title[] = {"B", "I", "N", "G", "O"};
for (int i = 0; i < title.length; i++) {
System.out.print(title[i] + "\t");
}
System.out.println();
for (int row = 0; row < card.length; row++) {
for (int col = 0; col < card[row].length; col++) {
System.out.print(card[row][col] + "\t");
}
System.out.println();
}
return bingo;
}
public static void main(String args[]) {
try {
ServerSocket serversct = new ServerSocket(1000);
int counter = 0;
System.out.println("Server Started ....");
while (counter <= 2) {
counter++;
Socket serverClient = serversct.accept(); //server accept the client connection request
System.out.println(" >> " + "Client No:" + counter + " started!");
DataInputStream inStream = new DataInputStream(serverClient.getInputStream());
DataOutputStream outStream = new DataOutputStream(serverClient.getOutputStream());
//bingo=Server.bingoCard();
ObjectOutputStream os = new ObjectOutputStream(serverClient.getOutputStream());
ServerClientThread sct = new ServerClientThread(serverClient, counter, inStream, outStream, os, new Server().bingoCard()); //send the request to a separate thread
ServerClientThread.sockets.add(sct);
if (counter == 1) {
ServerClientThread.chance.add(1);
} else {
ServerClientThread.chance.add(0);
}
}
ServerClientThread.distribute();
//ServerClientThread.sockets.get(1).start();
ServerClientThread.transferring();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ServerClientThread extends Thread {
Socket serverClient;
int clientNo;
DataInputStream inStream;
DataOutputStream outStream;
ObjectOutputStream oos;
static ArrayList<ServerClientThread> sockets = new ArrayList<>();
static ArrayList<Integer> chance = new ArrayList<>();
static ArrayList<ObjectOutputStream> oosal = new ArrayList<>();
static ArrayList<DataInputStream> datainputal = new ArrayList<>();
static ArrayList<DataOutputStream> dataoutputal = new ArrayList<>();
static int received;
int[][] card = new int[5][5];
int[][] bingo = new int[5][5];
ServerClientThread(Socket inSocket, int counter, DataInputStream dis, DataOutputStream dos, ObjectOutputStream oos, int abc[][]) {//,int abc[][]) {
this.serverClient = inSocket;
this.clientNo = counter;
this.oos = oos;
oosal.add(oos);
this.inStream = dis;
this.outStream = dos;
ServerClientThread.datainputal.add(dis);
ServerClientThread.dataoutputal.add(dos);
this.bingo = abc;
}
//i will use this run method later for checking winner of bingo card
#Override
public void run() {
try {
System.out.println("thread is running");
} catch (Exception ex) {
System.out.println(ex);
} finally {
System.out.println("Client :" + clientNo + " exit!! ");
}
}
public static void distribute() throws Exception {
System.out.println("distributing");
for (int i = 0; i <= ServerClientThread.sockets.size() - 1; i++) {
oosal.get(i).writeObject(ServerClientThread.sockets.get(i).bingo);
System.out.println("i is +" + i);
}
}
public static synchronized void transferring() throws Exception {
while (true) {
int chance = 1;
int received = 10000;
for (int i = 0; i <= ServerClientThread.datainputal.size() - 1; i++) {
ServerClientThread.dataoutputal.get(i).writeInt(chance);
ServerClientThread.dataoutputal.get(i).flush();
for (int l = 0; l <= ServerClientThread.chance.size() - 1; l++) {
if (ServerClientThread.chance.get(l) == 1)
{
received = ServerClientThread.datainputal.get(i).readInt();
}
if (l == i + 1)
{
ServerClientThread.chance.set(l, 1);
}
else if (i == ServerClientThread.chance.size() - 1) {
ServerClientThread.chance.set(l, 0);
ServerClientThread.chance.set(0, 1);
} else {
ServerClientThread.chance.set(l, 0);
}
}
for (int n = 0; n< ServerClientThread.datainputal.size(); n++)
{
for (int j = 0; j< ServerClientThread.datainputal.size(); j++)
if(ServerClientThread.chance.get(n)==1 && ServerClientThread.datainputal.get(j).available()>0)
{
received=ServerClientThread.datainputal.get(j).read();
}}
System.out.println("this is received" + received);
chance = 0;
for (int j = 0; j <= ServerClientThread.dataoutputal.size() - 1; j++) {
ServerClientThread.dataoutputal.get(j).writeInt(chance);
ServerClientThread.dataoutputal.get(j).writeInt(received);
}
chance = 1;
for (int k = 0; k <= ServerClientThread.chance.size() - 1; k++) {
System.out.println("here is given chance" + ServerClientThread.chance.get(k));
}
}
}
}
}
}
Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
class Client {
static String completed[] = new String[5];
static int tosend;
static int received1;
public static void main(String args[]) throws Exception {
try {
// Scanner scn = new Scanner(System.in);
// getting localhost ip
InetAddress ip = InetAddress.getByName("localhost");
int flag = 1;
// establish the connection with server port 9999
Socket s = new Socket(ip, 1000);
DataInputStream discl = new DataInputStream(s.getInputStream());
DataOutputStream doscl = new DataOutputStream(s.getOutputStream());
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
int[][] array = (int[][]) is.readObject();
//create array to make title.
String title[] = {"B", "I", "N", "G", "O"};
for (int i = 0; i < title.length; i++) {
System.out.print(title[i] + "\t");
}
System.out.println();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
System.out.print(array[row][col] + "\t");
}
System.out.println();
}
while (true) {
int i = discl.readInt();
if (i == 1 )
{
System.out.println("inside i==1");
System.out.println("in if condition 1");
System.out.println("opening scanner");
tosend = new Scanner(System.in).nextInt();
doscl.writeInt(tosend);
} else if (i == 0) {
//sendComplete();
System.out.println("closing scanner");
System.out.println("inside i==2");
//completed = Bingo;
System.out.println("in if condition 0");
received1 = discl.readInt();
System.out.println(received1);
}
}
} catch (IOException | ClassNotFoundException e) {
}
}
}
Aactually i am developing Bingo card game, after distributing bingo card to each client, game begins and each client will play one by one and send a number to server and then server will send that number to all clients this is the repeatedly process,
as i said all client will send number one by one if client follow this flow then the execution of the program is as i want i am stucked on a situation that is if client enters two numbers at a time **then after completing all other clients chance ,when chance comes to that particular client who entered two numbers will not get chance and the second number entered by this client will be considered as his played number. i want to stop listening from server side to accept numbers if a client enters more than one number at a time.

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

Array throws NullPointerException in Java

I have the following little problem... I have this code that uses the method OpenFile() of one class ReadData to read a .txt file and also I have another class ArraysTZones used to create an object that stores 3 arrays (data1,data2,data3) and 3 integers (total1,total2,total3) returned by the method OpenFile(). The problem is that when I try to display each array (data1,data2,data3) using the method getArray() of ArrayTZones it stops and displays the error NullPointerException. Anyone knows how could I fix this?
public static void main (String args[]) throws IOException {
String fileName = ".//data.txt";
int[] def = new int[180];
try {
ReadData file = new ReadData(fileName);
ArraysTZones summaryatz = new ArraysTZones();
summaryatz = file.OpenFile();
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray1()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal1());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray2()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal2());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray3()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal3());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
Heres OpenFile()
public ArraysTZones OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfTimeZones = 3;
int[] data1 = new int[180];
int[] data2 = new int[180];
int[] data3 = new int[180];
int total1 = 0;
int total2 = 0;
int total3 = 0;
ArraysTZones atz = new ArraysTZones();
for (int i = 0; i < numberOfTimeZones; i++){
if (i == 0) {
String firstTimeZone = textReader.readLine();
String[] val = firstTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total1 += stats;
data1[u] = stats;
}
total1= total1/180;
atz.setTotal1(total1);
atz.setArray1(data1);
}
else
if (i == 1) {
String secondTimeZone = textReader.readLine();
String[] val = secondTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total2 += stats;
data2[u] = stats;
}
total2= total2/180;
atz.setTotal2(total2);
atz.setArray2(data2);
}
else {
String thirdTimeZone = textReader.readLine();
String[] val = thirdTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total3 += stats;
data3[u] = stats;
}
total3= total3/180;
atz.setTotal3(total3);
atz.setArray3(data3);
}
}
textReader.close();
return atz;
}
The getArray()
public int[] getArray1 () {
return data1;
}
And setArray()
public void setArray1 (int[] farray) {
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
The problem seems to be here
public void setArray1 (int[] farray)
{
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
You're declaring a new variable called data1 and storing the content of farray to it.
After that method is done, that variable will be removed, due to his scope.
Remove int[] from the line int[] data1 = new int[180]; (or just remove the whole line .. it is unnecessary) and your data will be stored in the correct variable that was declared for the class.
public void setArray1 (int[] farray) {
data1 = farray;
}
You have to initialize ArraysTZones

Categories