Why is my class constructor called repeatedly? - java

Recently I have been working on a program that can convert TeX-generated PDFs to a certain form of text that retains some semantically meaningful style information such as subscripts and superscripts.
When debugging it seems that there might be something very unusual going on with the PDFTextStripper class.
Here is my TeXUtil class that does most of the work.
import com.google.common.base.CharMatcher;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Stack;
public class TeXUtil {
private Stack<SSStatus> ssstatus;
private boolean accentMode;
private String fs;
private boolean mathMode;
private SymbolDB db;
private Hashtable<String, String> maccDict;
float endY;//Positions
float endX;
float Y;
int height;//Height
//boolean test;
public TeXUtil() throws IOException {
ssstatus = new Stack<SSStatus>();
fs = "rm";
accentMode = false;//as in the state of being right after an accent
mathMode = false;
db = new SymbolDB();
maccDict = new Hashtable<String, String>();
maccDict.put("\\vec","\\vec");
maccDict.put("\\widehat","\\widehat");
maccDict.put("\\widetilde","\\widetilde");
maccDict.put("\\^","\\hat");
maccDict.put("\\v","\\check");
maccDict.put("\\u","\\breve");
maccDict.put("\\`","\\grave");
maccDict.put("\\~","\\tilde");
maccDict.put("\\=","\\bar");
maccDict.put("\\.","\\dot");
maccDict.put("\\","\\ddot");
maccDict.put("\\'","\\acute");
endY = 0;
endX = 0;
Y = 0;
height = 0;
//test = false;
System.out.println("TeXUtil initialized!");
}
private static String fontShortName(PDFont font) {
String[] segments = font.getName().split("\\+");
return segments[segments.length - 1];
}
private static int fontHeight(PDFont font) {
CharMatcher matcher = CharMatcher.inRange('0', '9');
return Integer.parseInt(matcher.retainFrom(fontShortName(font)));
}
private static String fontClass(PDFont font) {
CharMatcher matcher = CharMatcher.inRange('A', 'Z');
return (matcher.retainFrom(fontShortName(font))).toLowerCase();
}
private String textToTeX(String shortFontName, int code) throws JSONException {
JSONObject info = db.getInfo(shortFontName, code);
return info.getString("value");
}
public String fullTextToTeX(PDFont font, int code, float newEndX, float newY, float newEndY){
String shortFontName = fontClass(font);
try {
JSONObject info = db.getInfo(shortFontName, code);
String teXCode = info.getString("value");
StringBuilder preamble1 = new StringBuilder("");
StringBuilder preamble2 = new StringBuilder("");
StringBuilder postamble = new StringBuilder("");
boolean text = info.getBoolean("text");
boolean math = info.getBoolean("math");
boolean tacc = info.getBoolean("tacc");
boolean macc = info.getBoolean("macc");
String newFont = info.getString("font");
int newHeight = fontHeight(font);
//Font change, rm is seen as having no font
if (!newFont.equals(fs)) {
if (!fs.equals("rm"))
preamble1.insert(0, '}');
if (!newFont.equals("rm")) {
preamble2.append('\\');
preamble2.append(newFont);
preamble2.append('{');
}
preamble1.insert(0, " fs = " + fs + " nFs = " + newFont + "\n");
fs = newFont;
}
if (height == 0) {
//preamble2.append(" Meow! am = " + accentMode + " fs = " + fs + " mm = " + mathMode + "\n");
}
//Subscripts/Superscripts
if (height > newHeight && newEndX > endX) {//New subscript/superscript
if (newEndY < endY) {//New superscript
//ssstatus.push(SSStatus.SUP);
preamble2.insert(0, "^{");
}
else if (newY > Y) {//New subscript
//ssstatus.push(SSStatus.SUB);
preamble2.insert(0, "_{");
}
//else {
// System.out.println("Please investigate the situation: texcode = " + teXCode + "endY = " + endY + " Y=" + Y + " endX=" + endX + " newEndY=" + newEndY + " newY=" + newY + " newEndX= " + newEndX);
//}
}
else if (height < newHeight && height != 0) {
//ssstatus.pop();
preamble1.append('}');
}
height = newHeight;
endX = newEndX;
endY = newEndY;
Y = newY;
//Enter or leave math mode
if (mathMode && !math && !macc) {
mathMode = false;
preamble1.append('$');
}
else if (!mathMode && !text && !tacc) {
mathMode = true;
preamble2.insert(0,'$');
}
//Accents
if (accentMode) {//If accent mode is ever entered we need to leave it at once
postamble.append('}');
accentMode = false;
}
if ((mathMode && macc) || (!mathMode && tacc)) {//Right now assume that anything that can be an accent is an accent
postamble.append('{');
if (mathMode)
teXCode = maccDict.get(teXCode);
accentMode = true;
}
if (teXCode.charAt(0) == '\\')
return preamble1.toString() + preamble2.toString() + teXCode + ' ' + postamble.toString();
else
return preamble1.toString() + preamble2.toString() + teXCode + postamble.toString();
}
catch(JSONException e) {
return "\\" + shortFontName + "{" + code + "}";
}
}
}
Here is the main class.
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import com.google.common.base.CharMatcher;
import org.json.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Stack;
public class TEX2TXT {
public static void main(String args[]) throws IOException {
TeXUtil util = new TeXUtil();
//Loading an existing document
File file = new File("/Users/CatLover/Documents/Tex/Examples/c4.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper() {
protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
TeXUtil util = new TeXUtil();
StringBuilder builder = new StringBuilder();
for(TextPosition position: textPositions) {
float Y = position.getY();
float endY = position.getEndY();
float endX = position.getEndX();
PDFont font = position.getFont();
int[] codes = position.getCharacterCodes();
for(int code: codes) {
builder.append(util.fullTextToTeX(font, code, endX, Y, endY));
}
}
writeString(builder.toString());
}
};
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
System.out.println(text);
//Closing the document
document.close();
}
What's really weird is that TeXUtil is constructed every time any white space between words appear while TeXUtil() should be called only once. I'm not sure why this is the case. Since the PDFs are produced by LaTeX and LaTeX does not put white space characters in PDFs but instead leave space between characters to implicitly represent white spaces this may affect how PDFBox works.

You're constructing a new TeXUtil in the first line of your PDFTextStripper subclass's writeString method. If you just remove that line, it should be able to still reference the util defined in your main method (though depending on the version of java you're using, you may have to make it final).

Related

Java - Nested For loop - Better way to append to File for every System.out.println

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

Java prediction error Random not working? [closed]

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?

Cannot read a txt file

import java.io.*;
public class Point {
private double x;
private double y;
public Point(double x_coord, double y_coord) {
x = x_coord;
y = y_coord;
}
}
public class PointArray {
private Point points[];
public PointArray(FileInputStream fileIn) throws IOException {
try {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(fileIn));
int numberOfPoints = Integer.parseInt(inputStream.readLine())...points = new Point[numberOfPoints];
int i = 0;
String line;
while ((line = inputStream.readLine()) != null) {
System.out.print(line);
double x = Double.parseDouble(line.split(" ")[0]);
double y = Double.parseDouble(line.split(" ")[1]);
points[i] = new Point(x, y);
i++;
}
inputStream.close();
} catch (IOException e) {
System.out.println("Error");
System.exit(0);
}
}
}
public String toString() {
String format = "{";
for (int i = 0; i < points.length; i++) {
if (i < points.length - 1) format = format + points[i] + ", ";
else format = format + points[i];
}
format = format + "}";
return format;
}
public static void main(String[] args) {
FileInputStream five = new FileInputStream(new File("fivePoints.txt"));
PointArray fivePoints = new PointArray(five);
System.out.println(fivePoints.toString());
}
The txt file fivePoints is as shown below:
5
2 7
3 5
11 17
23 19
150 1
The first number in the first line means the number of points in the text file.
There is an error when I read the file. The output I want to get is {(2.0, 7.0), (3.0, 5.0), (11.0,17.0), (23.0, 19.0), (150.0, 1.0)}. How can I fix it?
Add a toString method to your Point which formats the Point as x, y
public class Point {
//...
#Override
public String toString() {
return x + ", " + y;
}
}
Move your toString method so it's defined in PointArray, you might also consider making use of StringJoiner to make your life simpler
public class PointArray {
//...
#Override
public String toString() {
StringJoiner sj = new StringJoiner(", ", "{", "}");
for (int i = 0; i < points.length; i++) {
sj.add("(" + points[i].toString() + ")");
}
return sj.toString();
}
}

Wordsearch puzzle nullpointerexception on array

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++)
{
..........
............
}
}

Can't see contents of JFrame until I drag open window

this is actually my first complete program which will eventually be used to write code for a robot I am making. Everything is working okay, except that when I run it, I have to drag open the window in order to see the content inside it.
Any suggestions on how to fix it.
frame2 - "click to build file" works.
frame - the one with the button grid, is the one I have to drag open to see.
Here is the setup file for frame (the one that doesn't work)
package Grid;
//march 13 to April 11
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class ButtonGrid extends JFrame {
public static int clicked[][] = new int[20][40];
static JButton button[] = new JButton[800];
static int x;
static int count = 1;
public static int clickedfinal[][];
int value;
public ButtonGrid() {
JFrame frame = new JFrame();
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
GridLayout grid = new GridLayout(20, 40, 10, 8);
frame.setLayout(grid);
for (int c = 0; c < 20; c++) {
for (int d = 0; d < 40; d++) {
clicked[c][d] = 0;
}
}
for (x = 0; x < 800; x++) {
button[x] = new JButton();
button[x].setActionCommand(Integer.toString(x));
frame.add(button[x]);
button[x].setBackground(Color.LIGHT_GRAY);
button[x].setOpaque(true);
thehandler handler = new thehandler();
button[x].addActionListener(handler);
}
}
public class thehandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
for (;;) {
value = Integer.parseInt(e.getActionCommand());
button[value].setBackground(Color.BLACK);
int r = value % 40;
int m = ((value - (value % 40)) / 40);
// learn how to round up
clicked[m][r] = 1;
break;
}
}
}
public static void main(String[] args) {
new ButtonGrid();
}
}
Here is the file for frame2, the one that does work; To test just run this one.
package Grid;
import javax.swing.JButton;
import javax.swing.JFrame;
import Grid.ButtonGrid;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
#SuppressWarnings("serial")
public class Arduinowriter extends JFrame {
static int t = 1;
static int buttonpressed;
static int total;
static String Code;
static String oldcode;
public Arduinowriter() {
JFrame frame2 = new JFrame("Build File");
JButton button = new JButton("Click to Build File");
frame2.setSize(400, 400);
frame2.add(button);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setVisible(true);
button.setActionCommand(Integer.toString(1));
thehandler handler = new thehandler();
button.addActionListener(handler);
}
public class thehandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
buttonpressed = Integer.parseInt(e.getActionCommand());
String newLine = System.getProperty("line.separator");
String Motor2_half = "digitalWrite(Motor2, HIGH);" + newLine
+ "delay(500)" + newLine + "digitalWrite(Motor2, LOW)";
String Motor2_one = "digitalWrite(Motor2, HIGH);" + newLine
+ "delay(1000);" + newLine + "digitalWrite(Motor2, LOW);";
String Servo1_dispense = "digitalWrite(Servo1, HIGH);" + newLine
+ "delay(1000)" + newLine + "digitalWrite(Servo1, LOW);";
String Motor2_back = "digitalWrite(Motor2back, High" + newLine
+ "delay(6000)" + newLine + "digitalWrite(Motor2back, Low)";
String Motor1_forward = "digitalWrite(Motor1, HIGH);" + newLine
+ "delay(1000);" + newLine + "digitalWrite(Motor1, LOW);";
String dispenseCycle = (Motor2_one + newLine + Servo1_dispense
+ " //Domino" + newLine);
String skipCycle = (Motor2_one + newLine);
String backCycle = (Motor1_forward + newLine + Motor2_back + newLine);
while (buttonpressed == 1) {
for (int x = 0; x < 20; x++) {
Code = oldcode + "//Line " + (x + 1);
oldcode = Code;
yloop: for (int y = 0; y < 40; y++) {
boolean empty = true;
for (int check = y; check < 39; check++) {
if (ButtonGrid.clicked[x][check] == 1) {
empty = false;
System.out.println(x + " not empty");
}
}
if (ButtonGrid.clicked[x][y] == 1 && y == 0) {
Code = oldcode + newLine + Servo1_dispense
+ " //Domino" + newLine;
} else if (ButtonGrid.clicked[x][y] == 1) {
Code = oldcode + newLine + dispenseCycle + newLine;
}
else if (ButtonGrid.clicked[x][y] == 0
&& empty == false) {
Code = oldcode + newLine + skipCycle + newLine;
} else {
Code = oldcode + newLine + backCycle + newLine;
oldcode = Code;
break yloop;
}
oldcode = Code;
}
}
try {
BufferedWriter out = new BufferedWriter(new FileWriter(
"C:\\ArduinoCode.txt"));
out.write(Code);
out.close();
} catch (IOException g) {
System.out.println("Exception ");
}
return;
}
}
}
// button
public static void main(String[] args) {
new ButtonGrid();
new Arduinowriter();
}
}
Note: I am a very beginner. This code has taken many many hours to write and I figured everything out using google and youtube. If anything in the code or what I have said is unclear or doesn't make sense, please forgive me and just ask.
Invoke frame.setVisible(true) after you set the layout manager and everything else that affects its "visual" state.

Categories