Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hello I have been working on a program that predicts numbers. I have went through the code several times now and edited it. For some reason teamOneScored is ALWAYS higher than teamTwoScored. This does not make any sense to me.
What is the error that is occurring?
Here is my CompareEngine Class:
package compare;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
import data.Main;
public class CompareEngine
{
public static void Comparison(int firstTeamTotal, int secondTeamTotal,
int[] firstPositionAmount, int[] secondPositionAmount, int[]
firstPosition, int[] secondPosition)
{
System.out.println(" Comparisons:");
System.out.println("----------------------------------------");
System.out.println(Main.firstTeam + " vs. " + Main.secondTeam);
System.out.println("----------------------------------------");
System.out.println(firstTeamTotal + " Total " + " " + secondTeamTotal);
System.out.println("");
System.out.println(firstPosition[0]-1+"-"+firstPosition[1]+"-"+firstPosition[2] + " Formation " + (secondPosition[0]-1) +"-"+secondPosition[1]+"-"+secondPosition[2]);
System.out.println("");
System.out.println(firstPosition[0] + " Defenders " + " " + secondPosition[0]);
System.out.println(firstPositionAmount[0] + " Defense Total " + " " + secondPositionAmount[0]);
System.out.println("");
System.out.println(firstPosition[1] + " Midfielders " + " " + secondPosition[1]);
System.out.println(firstPositionAmount[1] + " Midfield Total " + " " + secondPositionAmount[1]);
System.out.println("");
System.out.println(firstPosition[2] + " Attackers " + " " + secondPosition[2]);
System.out.println(firstPositionAmount[2] + " Attack Total " + " " + secondPositionAmount[2]);
}
public static void RunGame(int firstTeamTotal, int secondTeamTotal, int[] firstPositionAmount,
int[] secondPositionAmount, int[] firstPosition, int[] secondPosition) throws IOException
{
int depth;
System.out.println("What depth do you want to run?");
depth = Main.read.nextInt();
int firstShotCount = 0;
int secondShotCount = 0;
int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2;
int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2;
int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2;
int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2;
while(firstAttack*3 > secondDefense)
{
firstShotCount = firstShotCount + 1;
firstAttack = firstAttack - 5;
}
while(secondAttack*3 > firstDefense)
{
secondShotCount = secondShotCount + 1;
secondAttack = secondAttack - 5;
}
System.out.println(firstShotCount);
System.out.println(secondShotCount);
PossessionControl(Main.firstTeam, Main.secondTeam);
int[] teamOneScored = new int[99];
int[] teamTwoScored = new int[99];
int[] oneShotOn = new int[99];
int[] twoShotOn = new int[99];
int[] OnePossession = new int[99];
int[] TwoPossession = new int[99];
Random random = new Random();
for(int i = 0; i < depth; i++)
{
for(int x = 0; firstShotCount >= x; x++)
{
int shot = random.nextInt(10 - 1 + 1) + 1;
if (shot > 8)
{
teamOneScored[i] = teamOneScored[i] + 1;
}
if (shot > 4)
{
oneShotOn[i] = oneShotOn[i] + 1;
}
}
for(int y = 0; secondShotCount >= y; y++)
{
int shot = random.nextInt(10 - 1 + 1) + 1;
if (shot > 8)
{
teamTwoScored[i] = teamTwoScored[i] + 1;
}
if (shot > 4)
{
twoShotOn[i] = twoShotOn[i] + 1;
}
}
System.out.println(teamOneScored[i] + ":" + teamTwoScored[i]);
}
}
static File firstDataFile = new File("src/playerdata/" + Main.firstTeam);
static File secondDataFile = new File("src/playerdata/" + Main.secondTeam);
static int teamOnePossessionTotal = 0;
static int teamTwoPossessionTotal = 0;
public static void PossessionControl(String firstTeam, String secondTeam) throws IOException
{
BufferedReader br1 = new BufferedReader(new FileReader(firstDataFile));
String line = "";
for(int i = 1; i+1 < 13; i++)
{
line = br1.readLine();
teamOnePossessionTotal = teamOnePossessionTotal + PossessionStatTotal(line);
}
br1.close();
BufferedReader br2 = new BufferedReader(new FileReader(secondDataFile));
for(int i = 1; i+1 < 13; i++)
{
line = br2.readLine();
teamTwoPossessionTotal = teamTwoPossessionTotal + PossessionStatTotal(line);
}
br2.close();
}
public static int PossessionStatTotal(String line)
{
int value = 0;
String[] stats = line.split("-");
String position = stats[1];
if(!(position.equals("GK")))
{
String passing = stats[5];
String positioning = stats[7];
String ballControl = stats[9];
value = (int) ((int) (Integer.valueOf(passing)*.5) + Integer.valueOf(positioning)*.2 + Integer.valueOf(ballControl)*.1);
}
return value;
}
}
Here is my Main Class:
package data;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static String currentTeam;
public static void main(String[] args) throws IOException
{
compareTeams();
//setOveralls();
}
public static void setOveralls() throws IOException
{
Scanner read = new Scanner(System.in);
System.out.println("Which team do you like?");
currentTeam = read.nextLine();
read.close();
PlayerOverall.eraseOverallFile();
PlayerOverall.getPlayerInfo(13, currentTeam);
}
public static String firstTeam;
public static String secondTeam;
public static Scanner read = new Scanner(System.in);
public static void compareTeams() throws IOException
{
System.out.println("What is the first team?");
firstTeam = read.nextLine();
System.out.println("What is the second team?");
secondTeam = read.nextLine();
compare.CompareTeams.compare(firstTeam, secondTeam);
}
}
Here is the PlayerOverall Class, this just determines their Overall.
package data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PlayerOverall
{
//NOTE TO SELF -- CHANGE OUT OF HARD CODE VVVVVVVVVVV
static File dataFile = new File("src/playerdata/" + Main.currentTeam);
static File overallFile = new File("src/overalls/" + Main.currentTeam);
public static String getPlayerInfo(int numLine, String currentTeam) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(dataFile));
String line = "";
for(int i = 1; i+1 < numLine; i++)
{
line = br.readLine();
evaluatePlayer(line);
}
br.close();
return line;
}
public static void evaluatePlayer(String line) throws IOException
{
String[] stats = line.split("-");
String position = stats[1];
int overall = 0;
if(position.equals("GK"))
{
int height = Integer.parseInt(stats[2]);
int diving = Integer.parseInt(stats[3]);
int catching = Integer.parseInt(stats[4]);
int shooting = Integer.parseInt(stats[5]);
int reflexes = Integer.parseInt(stats[6]);
int positioning = Integer.parseInt(stats[7]);
overall = (int) ((int) ((int) ((int) ((int) ((int) (height*.05) + diving*.2) + catching*.2) + shooting*.1) + reflexes*.2) + positioning*.25);
setOverall(position, overall);
//OVERALL WORKS CORRECT NOW DO THE ADDITION OF OVERALL TO THE FILE!!
}
else
{
int speed = Integer.parseInt(stats[2]);
int acceleration = Integer.parseInt(stats[3]);
int distance = Integer.parseInt(stats[4]);
int passing = Integer.parseInt(stats[5]);
int shooting = Integer.parseInt(stats[6]);
int positioning = Integer.parseInt(stats[7]);
int defending = Integer.parseInt(stats[8]);
int ballControll = Integer.parseInt(stats[9]);
if(position.equals("LB") || position.equals("RB"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.1) + positioning*.15) + defending*.15) + ballControll*.1);
}
else if(position.equals("CB"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.095) + acceleration*.1) + distance*.1) + passing*.1) + shooting*.05) + positioning*.2) + defending*.3) + ballControll*.1);
}
else if(position.equals("CM"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.05) + acceleration*.05) + distance*.15) + passing*.2) + shooting*.1) + positioning*.2) + defending*.1) + ballControll*.1) + 10;
}
else if(position.equals("LM") || position.equals("RM"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.133) + positioning*.1) + defending*.033) + ballControll*.133) + 5;
}
else if(position.equals("ST"))
{
int stength = Integer.parseInt(stats[10]);
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.133) + acceleration*.133) + distance*.033) + passing*.05) + shooting*.225) + positioning*.225) + defending*.0) + ballControll*.1) + stength*.1) + 5;
}
setOverall(position, overall);
}
}
public static void setOverall(String position, int overall) throws IOException
{
try (FileWriter fw = new FileWriter(overallFile, true))
{
fw.append(position + "-" + overall +"\n");
}
}
public static void eraseOverallFile() throws IOException
{
FileWriter fw = new FileWriter(overallFile);
fw.write("");
fw.close();
}
}
The files I am getting for are just regular files. They look like this:
Lukas Hradecky-GK-63-81-81-74-89-82
Jetro Willems-LB-83-86-80-79-76-72-76-81
David Abraham-CB-76-83-68-74-70-76-80-61
Simon Falette-CB-60-71-77-57-50-74-84-56
Timmy Chandler-RB-80-76-83-74-68-71-77-74
Marco Fabian-CM-70-76-75-78-80-77-36-85
Jonathan De Guzman-CM-78-79-70-78-80-78-51-83
Mijat Gacinovic-RM-78-78-74-70-68-69-61-81
Ante Rebic-LM-76-79-71-62-78-72-40-75
Sebastien Haller-ST-75-79-73-64-77-77-35-79-91
Kevin Prince Boateng-ST-74-74-67-79-82-78-70-83-83
You can name this file whatever you like. Make another file in the appropriate location and it will generate everything else needed.
Thank you for your help!
I think you missed the minimal in [mcve].
TL;DR ... but spotted:
int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2;
int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2;
int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2;
int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2;
Indices are:
0 1
0 1
2 1
2 2
This seems inconsistent. Perhaps last should be a 1?
Related
Okay so i have to read data from an CSV file and add methods that calculate which is seen in my code below, so my question is how can i put in output the header of a row (example first,second or third) from which the value has been taken from?
Possibilites | first | second | third| fourth
Decrease | 28 | 24 | 16 | 25
Increase | 30 | 42 | 44 | 45
this is a CSV file im using
My output is like this:
Optimist: first (45)
Pessimist: second (30)
Laplace: third(33)
Least regret: fourth(5)
But i want it to be like this:
Optimist: fourth (45)
Pessimist: first(30)
Laplace: second (33)
Least regret: fourth(5)
package CSVReader;
import java.io.*;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.plaf.FileChooserUI;
import com.opencsv.CSVReader;
public class OpenCSV {
public static void main(String[] args) {
CSVReader reader;
String file = "C:\\Users\\pajov\\Desktop\\osnovne_metode1.csv";
String[] decreaseEconomyAlternatives = null;
String[] increaseEconomyAlternatives = null;
String[] headers = null;
int sizeOfDecisionAlternatives = 0;
try {
reader = new CSVReader(new FileReader(file));
List<String[]> allResults = reader.readAll();
sizeOfDecisionAlternatives = allResults.get(0).length - 1;
headers = allResults.get(0);
decreaseEconomyAlternatives = allResults.get(1);
increaseEconomyAlternatives = allResults.get(2);
System.out.println("Prebrana je bila datoteka: " + file);
for (int i = 1; i <= sizeOfDecisionAlternatives; i++) {
int iterator = i;
System.out.println("Optimist:"+headers[iterator] +" (" + calculationOptist(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
iterator++;
System.out.println("Pessimist:"+headers[iterator] + " (" + calculationPessimist(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
iterator++;
System.out.println("Laplace: "+headers[iterator] + " (" + calculationLaplace(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
iterator++;
System.out.println("Least regret: "+headers[iterator] + " (" + calculationLeastRegret(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private static Integer calculationLeastRegret(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfDecreasedValues = new ArrayList<>();
List<Integer> arrayOfIncreasedValues = new ArrayList<>();
List<Integer> maxNumbersOfNewArray = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives + 1; i++) {
arrayOfDecreasedValues.add(Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")));
arrayOfIncreasedValues.add(Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", "")));
}
Integer maxOfDereased = Collections.max(arrayOfDecreasedValues);
Integer maxOfIncreased = Collections.max(arrayOfIncreasedValues);
for (int i = 0; i < sizeOfDecisionAlternatives; i++) {
maxNumbersOfNewArray.add(Math.max((maxOfDereased - arrayOfDecreasedValues.get(i)), (maxOfIncreased - arrayOfIncreasedValues.get(i))));
}
return Collections.min(maxNumbersOfNewArray);
}
private static Integer calculationLaplace(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfNumbers = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives; i++) {
arrayOfNumbers.add((Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")) + Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", ""))) / 2);
}
return Collections.max(arrayOfNumbers);
}
private static Integer calculationPessimist(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfNumbers = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives + 1; i++) {
arrayOfNumbers.add(Math.min(Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")), Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", ""))));
}
return Collections.max(arrayOfNumbers);
}
private static Integer calculationOptist(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfNumbers = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives + 1; i++) {
arrayOfNumbers.add(Math.max(Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")), Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", ""))));
}
return Collections.max(arrayOfNumbers);
}
}
Thanks in advance.
I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.
I am using the below code to generate some Test Data which gets the job done. No problems here.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
System.out.println("\nCluster__________________________" + numCluster);
writeToFile("Cluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
System.out.println("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
System.out.println("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
writeToFile("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
System.out.println("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
private static void writeToFile(String data) throws IOException {
File file = new File("dbscript_output.sql");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write(data);
br.close();
fr.close();
}
}
Question: Is there a better way to achieve it? Does Java 7/8/11 has any better API to do it? I am open for any shorter/smarter way of doing it using Java. The sample shown here is just a few elements. I have 16 Entities for which I have to prepare Test Data and all of them are connected (related). Thanks.
UPDATE
Please allow me to reframe the question.
Is there any shorter/smarter way to achieve above using pure Core Java 1.8+ ? Where I can club (merge) 'for' loop and 'writeToFile'? (in one liner may be?) Appreciate all for your help.
As our colleague mentioned above you can use try with resources as below (so you dont have to close every input stream). You can also short/change nested for loops with streams but it isn't clearer solution and you have to improve it.
public class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
IntStream.range(0, totalCluster).forEach(numCluster->{
writeToFile("Cluster__________________________" + numCluster);
IntStream.range(0, totalAgency).forEach(numAgency->{
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
IntStream.range(0, totalProgramArea).forEach(numProgramArea->
IntStream.range(0,totalUsers).forEach(numUser->{
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}));
});
});
}
private static void writeToFile(String data) {
File file = new File("dbscript_output2.sql");
try(FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr)) {
br.write(data);
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It's better to only open the file once (as opposed to opening and closing it for each entry).
Also, you can use the try-with-resources statement to ensure that the output file is closed automatically.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
// try-with-resources statement
try (BufferedWriter br = new BufferedWriter(new FileWriter("dbscript_output.sql"))) {
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
writeOutput(br, "Cluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
writeOutput(br,"\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
writeOutput(br,"\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
writeOutput(br,"\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
}
private static void writeOutput(BufferedWriter br, String data) throws IOException {
System.out.println(data);
br.write(data);
}
}
In the alternative below the nested loops have been refactored into separate methods and the file is opened just once and closed once you're done with it. It's not shorter but perhaps a bit more readable. Anyway, hope this gives you some inspiration.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.function.Consumer;
import java.util.stream.IntStream;
class GenerateTestData {
static int TOTAL_CLUSTER = 2;
static int TOTAL_AGENCY = TOTAL_CLUSTER * 2;
static int TOTAL_PROGRAM_AREA = TOTAL_AGENCY * 2;
static int TOTAL_USERS = TOTAL_PROGRAM_AREA * 2;
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
try (BufferedWriter br = new BufferedWriter(new FileWriter(outfile, true))) {
createClusters(str -> writeLine(br, str));
}
}
private static void writeLine(BufferedWriter writer, String data) {
try {
System.out.println(data);
writer.write(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void createClusters(Consumer<String> consumer) {
IntStream.range(1, TOTAL_CLUSTER).forEach(numCluster -> {
consumer.accept("Cluster__________________________" + numCluster);
createAgencies(consumer, numCluster);
});
}
private static void createAgencies(Consumer<String> consumer, int numCluster) {
IntStream.range(1, TOTAL_AGENCY).forEach(numAgency -> {
consumer.accept("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
createProgramAreas(consumer, numAgency);
});
}
private static void createProgramAreas(Consumer<String> consumer, int numAgency) {
IntStream.range(1, TOTAL_PROGRAM_AREA).forEach(numProgramArea -> {
consumer.accept("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
createUsers(consumer, numAgency, numProgramArea);
});
}
private static void createUsers(Consumer<String> consumer, int numAgency, int numProgramArea) {
IntStream.range(1, TOTAL_USERS).forEach(numUser -> {
consumer.accept("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea + "_User_" + numUser);
});
}
}
Am getting a java.lang.NullPointerException on an array I have initialized and I can't quite figure it out what am doing wrong. The error is occuring at line 371.
Below is the code of the parent class followed by the class initializng the letterArray ArrayList:
package wordsearch;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
/**
* Main class of Puzzle Program
* #author mungaialex
*
*/
public class WordSearchPuzzle extends JFrame {
private static final long serialVersionUID = 1L;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
static JButton[][] grid; //names the grid of buttons
GridLayout myGridLayout = new GridLayout(1,2,3,3);
/**Array to hold wordList*/
ArrayList<String> wordList;
JButton btnCheck, btnClear;
/** Panel to hold Components to the left*/
JPanel leftSidePanel;
/** Panel to hold components to the right*/
JPanel rightSidePanel;
/**Panel to hold word List*/
JPanel wordListPanel;
/**Panel to hold grid buttons*/
JPanel gridPanel;
/**Panel to hold clear button and check button*/
JPanel buttonsPanel;
/**Panel to hold output textarea*/
JPanel bottomPanel;
private JLabel[] wordListComponents;
#SuppressWarnings("rawtypes")
List puzzleLines;
//Grid Size
private final int ROWS = 20;
private final int COLS = 20;
/** Output Area of system*/
private JTextArea txtOutput;
/**Scrollpane for Output area*/
private JScrollPane scptxtOutput;
private Object[] theWords;
public String wordFromChars = new String();
/** the matrix of the letters */
private char[][] letterArray = null;
/**
* Constructor for WordSearchPuzzle
* #param wordListFile File Containing words to Search for
* #param wordSearhPuzzleFile File Containing the puzzle
*/
public WordSearchPuzzle(String wordSearchFile,String wordsListFile) throws IOException {
FileIO io = new FileIO(wordSearchFile,wordsListFile,grid);
wordList = io.loadWordList();
theWords = wordList.toArray();
addComponentsToPane();
buildWordListPanel();
buildBottomPanel();
io.loadPuzleFromFile();
//Override System.out
PrintStream stream = new PrintStream(System.out) {
#Override
public void print(String s) {
txtOutput.append(s + "\n");
txtOutput.setCaretPosition(txtOutput.getText().length());
}
};
System.setOut(stream);
System.out.print("MESSAGES");
}
/**
* Constructor two
*/
public WordSearchPuzzle() {
}
/**
* Gets the whole word of buttons clicked
* #return
* Returns whole Word
*/
public String getSelectedWord() {
return wordFromChars;
}
/**
* Adds word lists to Panel on the left
*/
private void buildWordListPanel() {
leftSidePanel.setBackground(Color.WHITE);
// Build the word list
wordListComponents = new JLabel[wordList.size()];
wordListPanel = new JPanel(new GridLayout(25, 1));
wordListPanel.setBackground(Color.white);
//Loop through list of words
for (int i = 0; i < this.wordList.size(); i++) {
String word = this.wordList.get(i).toUpperCase();
wordListComponents[i] = new JLabel(word);
wordListComponents[i].setForeground(Color.BLUE);
wordListComponents[i].setHorizontalAlignment(SwingConstants.LEFT);
wordListPanel.add(wordListComponents[i]);
}
leftSidePanel.add(wordListPanel,BorderLayout.WEST);
}
/**
* Adds an output area to the bottom of
*/
private void buildBottomPanel() {
bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
txtOutput = new JTextArea();
txtOutput.setEditable(false);
txtOutput.setRows(5);
scptxtOutput = new JScrollPane(txtOutput);
bottomPanel.add(txtOutput,BorderLayout.CENTER);
bottomPanel.add(scptxtOutput,BorderLayout.SOUTH);
rightSidePanel.add(bottomPanel,BorderLayout.CENTER);
}
/**
* Initialize Components
*/
public void addComponentsToPane() {
// buttonsPanel = new JPanel(new BorderLayout(3,5)); //Panel to hold Buttons
buttonsPanel = new JPanel(new GridLayout(3,1));
leftSidePanel = new JPanel(new BorderLayout());
rightSidePanel = new JPanel(new BorderLayout());
btnCheck = new JButton("Check Word");
btnCheck.setActionCommand("Check");
btnCheck.addActionListener(new ButtonClickListener());
btnClear = new JButton("Clear Selection");
btnClear.setActionCommand("Clear");
btnClear.addActionListener(new ButtonClickListener());
buttonsPanel.add(btnClear);//,BorderLayout.PAGE_START);
buttonsPanel.add(btnCheck);//,BorderLayout.PAGE_END);
leftSidePanel.add(buttonsPanel,BorderLayout.SOUTH);
this.getContentPane().add(leftSidePanel,BorderLayout.LINE_START);
gridPanel = new JPanel();
gridPanel.setLayout(myGridLayout);
myGridLayout.setRows(20);
myGridLayout.setColumns(20);
grid = new JButton[ROWS][COLS]; //allocate the size of grid
//theBoard = new char[ROWS][COLS];
for(int Row = 0; Row < grid.length; Row++){
for(int Column = 0; Column < grid[Row].length; Column++){
grid[Row][Column] = new JButton();//Row + 1 +", " + (Column + 1));
grid[Row][Column].setActionCommand(Row + "," + Column);
grid[Row][Column].setActionCommand("gridButton");
grid[Row][Column].addActionListener(new ButtonClickListener());
gridPanel.add(grid[Row][Column]);
}
}
rightSidePanel.add(gridPanel,BorderLayout.NORTH);
this.getContentPane().add(rightSidePanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
try {
if (args.length !=2) { //Make sure we have both the puzzle file and word list file
JOptionPane.showMessageDialog(null, "One or All Files are Missing");
} else { //Files Found
WordSearchPuzzle puzzle = new WordSearchPuzzle(args[0],args[1]);
puzzle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
puzzle.setSize(new Dimension(1215,740));
//Display the window.
puzzle.setLocationRelativeTo(null); // Center frame on screen
puzzle.setResizable(false); //Set the form as not resizable
puzzle.setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public int solvePuzzle( ){
int matches = 0;
for( int r = 0; r < ROWS; r++ )
for( int c = 0; c < COLS; c++ )
for( int rd = -1; rd <= 1; rd++ )
for( int cd = -1; cd <= 1; cd++ )
if( rd != 0 || cd != 0 )
matches += solveDirection( r, c, rd, cd );
return matches;
}
private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta ){
String charSequence = "";
int numMatches = 0;
int searchResult;
FileIO io = new FileIO();
charSequence += io.theBoard[ baseRow ][ baseCol ];
for( int i = baseRow + rowDelta, j = baseCol + colDelta;
i >= 0 && j >= 0 && i < ROWS && j < COLS;
i += rowDelta, j += colDelta )
{
charSequence += io.theBoard[ i ][ j ];
searchResult = prefixSearch( theWords, charSequence );
if( searchResult == theWords.length )
break;
if( !((String)theWords[ searchResult ]).startsWith( charSequence ) )
break;
if( theWords[ searchResult ].equals( charSequence ) )
{
numMatches++;
System.out.println( "Found " + charSequence + " at " +
baseRow + " " + baseCol + " to " +
i + " " + j );
}
}
return numMatches;
}
private static int prefixSearch( Object [ ] a, String x ) {
int idx = Arrays.binarySearch( a, x );
if( idx < 0 )
return -idx - 1;
else
return idx;
}
class ButtonClickListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String command = ((JButton)e.getSource()).getActionCommand();
if (command == "Clear") {
//Enable the buttons that have been disabled and not form a whole word
//JOptionPane.showMessageDialog(null, "Cooming Soon");
for (String word : wordList) {
System.out.print(word);
}
} else if (command == "Check") {
String selectedWord = getSelectedWord();
if (!selectedWord.equals("")){
System.out.print("Selected word is " + getSelectedWord());
//First check if selected word exits in wordList
if (ifExists(selectedWord)) {
if(searchWord(selectedWord)){
JOptionPane.showMessageDialog(null, "Success");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "[" + selectedWord + "] " +
"Does Not Belong to Word list");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "No Buttons on Grid have been clicked");
}
} else if (command == "gridButton") {
getSelectedCharacter(e);
((JButton)e.getSource()).setEnabled(false);
}
}
/**
* Gets the character of each button and concatenates each character to form a whole word
* #param e The button that received the Click Event
* #return Whole word
*/
private String getSelectedCharacter (ActionEvent e) {
String character;
character = ((JButton) e.getSource()).getText();
wordFromChars = wordFromChars + character;
return wordFromChars;
}
}
/**
* Checks if selected word is among in wordlist
* #param selectedWord
* #return The word to search for
*/
private boolean ifExists(String selectedWord) {
if (wordList.contains(selectedWord)) {
return true;
}
return false;
}
public boolean searchWord(String word) {
if (!wordList.contains(word)) {
return false;
}
//int index = wordList.indexOf(word);
Line2D.Double line = new Line2D.Double();
//System.out.print("LetterArray is " + letterArray.length);
for (int x = 0; x < letterArray.length; x++) {
for (int y = 0; y < letterArray[x].length; y++) {
// save start point
line.x1 = y; // (y + 1) * SCALE_INDEX_TO_XY;
line.y1 = x; // (x + 1) * SCALE_INDEX_TO_XY;
int pos = 0; // current letter position
if (letterArray[x][y] == word.charAt(pos)) {
// first letter correct -> check next
pos++;
if (pos >= word.length()) {
// word is only one letter long
// double abit = SCALE_INDEX_TO_XY / 3;
line.x2 = y; // (y + 1) * SCALE_INDEX_TO_XY + abit;
line.y2 = x; // (x + 1) * SCALE_INDEX_TO_XY + abit;
return true;
}
// prove surrounding letters:
int[] dirX = { 1, 1, 0, -1, -1, -1, 0, 1 };
int[] dirY = { 0, -1, -1, -1, 0, 1, 1, 1 };
for (int d = 0; d < dirX.length; d++) {
int dx = dirX[d];
int dy = dirY[d];
int cx = x + dx;
int cy = y + dy;
pos = 1; // may be greater if already search in another
// direction from this point
if (insideArray(cx, cy)) {
if (letterArray[cx][cy] == word.charAt(pos)) {
// 2 letters correct
// -> we've got the direction
pos++;
cx += dx;
cy += dy;
while (pos < word.length() && insideArray(cx, cy)
&& letterArray[cx][cy] == word.charAt(pos)) {
pos++;
cx += dx;
cy += dy;
}
if (pos == word.length()) {
// correct end if found
cx -= dx;
cy -= dy;
pos--;
}
if (insideArray(cx, cy) && letterArray[cx][cy] == word.charAt(pos)) {
// we've got the end point
line.x2 = cy; // (cy + 1) *
// SCALE_INDEX_TO_XY;
line.y2 = cx; // (cx + 1) *
// SCALE_INDEX_TO_XY;
/*
* System.out.println(letterArray[x][y] +
* " == " + word.charAt(0) + " (" + line.x1
* + "," + line.y1 + ") ->" + " (" + line.x2
* + "," + line.y2 + "); " + " [" + (line.x1
* / SCALE_INDEX_TO_XY) + "," + (line.y1 /
* SCALE_INDEX_TO_XY) + "] ->" + " [" +
* (line.x2 / SCALE_INDEX_TO_XY) + "." +
* (line.y2 / SCALE_INDEX_TO_XY) + "]; ");
*/
//result[index] = line;
// found
return true;
}
// else: try next occurence
}
}
}
}
}
}
return false;
}
private boolean insideArray(int x, int y) {
boolean insideX = (x >= 0 && x < letterArray.length);
boolean insideY = (y >= 0 && y < letterArray[0].length);
return (insideX && insideY);
}
public void init(char[][] letterArray) {
try {
for (int i = 0; i < letterArray.length; i++) {
for (int j = 0; j < letterArray[i].length; j++) {
char ch = letterArray[i][j];
if (ch >= 'a' && ch <= 'z') {
letterArray[i][j] = Character.toUpperCase(ch);
}
}
}
} catch (Exception e){
System.out.println(e.toString());
}
//System.out.println("It is " + letterArray.length);
this.letterArray = letterArray;
}
}
Here is class initializing the letterArray array:
package wordsearch;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
/**
* Reads wordlist file and puzzle file
* #author mungaialex
*
*/
public class FileIO {
String _puzzleFile, _wordListFile;
/**ArrayList to hold words*/
ArrayList<String> wordList;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
List puzzleLines;
JButton[][] _grid;
char theBoard[][];
private final int _rows = 20;
private final int _columns = 20;
WordSearchPuzzle pz = new WordSearchPuzzle();
/**
* Default Constructor
* #param puzzleFile
* #param wordListFile
*/
public FileIO(String puzzleFile, String wordListFile,JButton grid[][]){
_puzzleFile = new String(puzzleFile);
_wordListFile = new String(wordListFile);
_grid = pz.grid;
}
public FileIO() {
}
/**
* Reads word in the wordlist file and adds them to an array
* #param wordListFilename
* File Containing Words to Search For
* #throws IOException
*/
protected ArrayList<String> loadWordList()throws IOException {
int row = 0;
wordList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(_wordListFile));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() != WORDLISTCOLS) {
JOptionPane.showMessageDialog(null, "Error: only one word per line allowed in the word list",
"WordSearch Puzzle: Invalid Format", row);//, JOptionPane.OK_CANCEL_OPTION);
//"Error: only one word per line allowed in the word list");
}
String tok = tokenizer.nextToken();
wordList.add(tok.toUpperCase());
line = reader.readLine();
row++;
}
reader.close();
return wordList;
}
/**
* Reads the puzzle file line by by line
* #param wordSearchFilename
* The file containing the puzzle
* #throws IOException
*/
protected void loadPuzleFromFile() throws IOException {
int row = 0;
BufferedReader reader = new BufferedReader(new FileReader(_puzzleFile));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
puzzleLines = new ArrayList<String>();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
int col = 0;
sb.append(line);
sb.append('\n');
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
WordSearchPuzzle.grid[row][col].setText(tok);
pz.grid[row][col].setForeground(Color.BLACK);
pz.grid[row][col].setHorizontalAlignment(SwingConstants.CENTER);
puzzleLines.add(tok);
col++;
}
line = reader.readLine();
row++;
theBoard = new char[_rows][_columns];
Iterator itr = puzzleLines.iterator();
for( int r = 0; r < _rows; r++ )
{
String theLine = (String) itr.next( );
theBoard[ r ] = theLine.toUpperCase().toCharArray( );
}
}
String[] search = sb.toString().split("\n");
initLetterArray(search);
reader.close();
}
protected void initLetterArray(String[] letterLines) {
char[][] array = new char[letterLines.length][];
System.out.print("Letter Lines are " +letterLines.length );
for (int i = 0; i < letterLines.length; i++) {
letterLines[i] = letterLines[i].replace(" ", "").toUpperCase();
array[i] = letterLines[i].toCharArray();
}
System.out.print("Array inatoshana ivi " + array.length);
pz.init(array);
}
}
Thanks in advance.
Here it is!
char[][] array = new char[letterLines.length][];
You are only initializing one axis.
When you pass this array to init() and set this.letterArray = letterArray;, the letterArray is also not fully initialized.
Try adding a length to both axes:
char[][] array = new char[letterLines.length][LENGTH];
first you will handle the NullPoinetrException , the code is
if( letterArray != null){
for (int x = 0; x < letterArray.length; x++)
{
..........
............
}
}
I write vba macros, that create file in random access mode:
Private Type Record
id As Long
name As String * 20
status As String * 10
End Type
Private rec As Record
Private rows_count As Long
Private datfilePath As String
Private Sub writeButton_Click()
datfilePath = ThisWorkbook.Path + "\data\datfile.dat"
datfile = FreeFile()
Open datfilePath For Random As #datfile Len = Len(rec)
rows_count = Int(LOF(datfile) / Len(rec))
rec.id = rows_count + 1
rec.name = "test_name_" + Str(rows_count + 1)
rec.status = "test_sta" + Str(rows_count + 1)
Put #datfile, rows_count + 1, rec
rows_count = Int(LOF(datfile) / Len(rec))
Close #datfile
End Sub
how to read created file in java?
in result:
import java.io.*;
class ReadVBFile {
public static void main(String[] args) throws IOException{
try
{
String file = "datfile.dat";
RandomAccessFile fh = new RandomAccessFile(file,"r");
int file_length =(int)fh.length();
int rec_length = 34;
int rec_count = (int)(file_length/rec_length);
System.out.println("file_length: " + file_length + "\r\n");
System.out.println("rec_count: " + rec_count + "\r\n");
for( int i_row=0; i_row < rec_count; i_row++ )
{
byte[] id_array = new byte[4];
byte[] name_array = new byte[20];
byte[] status_array = new byte[10];
for( int i=0; i < 34; i++ )
{
byte b = fh.readByte();
if( i < 4 )
{
id_array[i] = b;
}
else if( i < 24 )
{
name_array[i-4] = b;
}
else if( i < 34 )
{
status_array[i-24] = b;
}
fh.seek( i_row*34 + i + 1 );
}
// Long as Int
int myInt = ((id_array[1] & 0xff) << 24) | ((id_array[2] & 0xff) << 16) | ((id_array[3] & 0xff) << 8) | (id_array[0] & 0xff);
String name_value = new String(name_array);
String status_value = new String(status_array);
System.out.println( myInt + ", '" + name_value + "', '" + status_value + "'");
}
}
catch(IOException e)
{
System.out.println( "IOException: " + e.getMessage() );
}
catch(Exception e)
{
System.out.println( "Exception: " + e.getMessage() );
}
}
}