Printing ArrayList of 2D arrays in a specific format - java

I'm trying to save an ArrayList to a text file in a particular format. It's in the correct format but it only prints out the color of one element in the ArrayList of blocks. I know the problem lies with the getBlockColor() method, what's the best way to implement this method? Here's what I've got so far.
This is the method that is in the class with the ArrayList of frames.
public void saveFrames(String fileName) {
System.out.println("**method save writes data back to a file "
+ fileName);
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(fileName)));
outfile.println(frames.size());
outfile.println(Frame.getCOLUMNS());
for (Frame f : frames) {
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
Color a = f.getBlockColor();
if (a.equals(Color.white)) {
outfile.print("w");
}
if (a.equals(Color.orange)) {
outfile.print("o");
}
if (a.equals(Color.red)) {
outfile.print("r");
}
if (a.equals(Color.yellow)) {
outfile.print("y");
}
if (a.equals(Color.green)) {
outfile.print("g");
}
if (a.equals(Color.blue)) {
outfile.print("b");
}
}
outfile.println("");
}
}
outfile.close();
}
catch (IOException e) {
System.out.println("file not found try again");
}
}
This is the code from the frame that is supposed to get the color of the blocks.
public Color getBlockColor() {
for (int ROWS = 0; ROWS < 20; ROWS++) {
for (int COLUMNS = 0; COLUMNS < 20; COLUMNS++) {
blockColor = blocks[ROWS][COLUMNS].getBackground();
}
}
return blockColor;
}

I think you made a small mistake in getting the block color.
I guess you were supposed to return the color for a specific row and column, like this:
public Color getBlockColor(int row, int column) {
return blocks[row][column].getBackground();
}

Related

How to change dxf layer color in java using jdxf library?

I have a java code generating dxf files, I am using jdxf library. Almost everything works fine with it, there is only one thing I could not figure out. When I'm adding a new Layer, I wish to do it with a new color so that all entities I draw under this new layer shall have a "ByLayer" color, which would be this new color I specify.
I can only achieve that the entities shall have the color I specify, but their layer's default color would still be black/white. Here is my DXFHandler object:
public class DXFHandler {
//https://jsevy.com/wordpress/index.php/java-and-android/jdxf-java-dxf-library/
DXFGraphics graphics;
DXFDocument dXFDocument;
int mirrorY, mirrorX;
public DXFHandler() {
dXFDocument = new DXFDocument();
dXFDocument.setUnits(4);//set units to mm
dXFDocument.setPrecisionDigits(1);//set precision digits
dXFDocument.setViewportCenter(0, 0);
graphics = dXFDocument.getGraphics();
mirrorX=1;
mirrorY=-1;
}
public void addLayer(String layerName, Color c) {
dXFDocument.setLayer(layerName);
graphics.setColor(c);//This will only achieve that the drawing entities get this color, but the layer's color would not be touched.
}
public void drawLine(double[]x, double[]y){
if (x!=null&&y!=null&x.length==y.length) {
for (int i = 1; i < x.length; i++) {
graphics.drawLine(mirrorX*x[i-1], mirrorY*y[i-1],mirrorX*x[i],mirrorY*y[i]);
}
}
}
public void drawPoint(double[]x, double[]y){
if (x!=null&&y!=null&x.length==y.length) {
for (int i = 0; i < x.length; i++) {
graphics.drawPoint(mirrorX*x[i], mirrorY*y[i]);
}
}
}
public void drawRect(double x1, double y1, double x2, double y2){
graphics.drawRect(mirrorX*x1, mirrorY*y1, mirrorX*x2, mirrorY*y2);
}
public void saveToDXF(String outputPath) throws IOException {
String stringOutput = dXFDocument.toDXFString();
FileWriter fileWriter = new FileWriter(outputPath);
fileWriter.write(stringOutput);
fileWriter.flush();
fileWriter.close();
}
And here is an example code to test it:
public static void main(String[] args) {
String outputFile="d:\\test.dxf";
int points=500;//Number of drawn points .
String layer1Name="Layer_1";
double[]xCoordinatesOfPoints1=new double[points];//creating first test-pointset_Xcoordinates
double[]yCoordinatesOfPoints1=new double[points];//creating first test-pointset_Ycoordinates
for (int i = 0; i < xCoordinatesOfPoints1.length; i++) {
xCoordinatesOfPoints1[i]=i;
yCoordinatesOfPoints1[i]=i;
}
String layer2Name="Layer_2";
double[]xCoordinatesOfPoints2=new double[points];//creating second test-pointset_Xcoordinates
double[]yCoordinatesOfPoints2=new double[points];//creating second test-pointset_Ycoordinates
for (int i = 0; i < xCoordinatesOfPoints1.length; i++) {
xCoordinatesOfPoints2[i]=-1*i;
yCoordinatesOfPoints2[i]=i;
}
DXFHandler dXFHandler=new DXFHandler(); //Creating dxf handler object
dXFHandler.addLayer(layer1Name, Color.red);//Creating layer1
dXFHandler.drawPoint(xCoordinatesOfPoints1, yCoordinatesOfPoints1);//drawing points of layer1
dXFHandler.addLayer(layer2Name, Color.GREEN);//Creating layer2
dXFHandler.drawPoint(xCoordinatesOfPoints2, yCoordinatesOfPoints2);//drawing points of layer2
try {
dXFHandler.saveToDXF(outputFile);//Exporting dxf file
} catch (IOException ex) {
System.out.println("FAILED");
}
}
As a result I get a "test.dxf" file which has a green and red point-set. That would be fine but both layers' default color is white. I would prefer if the points' color was "ByLayer" and the layer color was green/red, as it is in my "wantedSolution.dxf", which I failed to see how to attach. I will attach it as soon as I figure out how to do that...

Java-Matrix multiplication failing in loop only

I'm a math student writing a program to help with my research, but a small flaw is holding me up and I'm not sure what's going wrong.
In the first two calls to the power method, the computation is correct. In the loop, the first power works fine, but the matrix that is made when j=2 is a 2x2 matrix, instead of the correct one I usually get!
I'm sorry if I haven't included enough information, but the program is becoming quite large and I'm unfamiliar with conventions in CS and on SO. I appreciate any help.
public Queue<OrdInt> tree(Matrix inputMatr) {
Queue<OrdInt> holder = new LinkedList<OrdInt>();
LinkedList<Matrix> powers = new LinkedList<Matrix>();
powers.add(Matrix.identity(inputMatr.size));
int Np=0;
int j=1;
while(!powers.contains(inputMatr.power(j)) && j<Math.pow(2, inputMatr.size)){
powers.add(inputMatr.power(j));
try {
Np = (2*powers.get(j).nullspaceDim() - powers.get(j-1).nullspaceDim() - powers.get(j).matrixMultiply(inputMatr).nullspaceDim());
System.out.println("J+1 dim: " +powers.get(j).matrixMultiply(inputMatr).size);
} catch (Exception e) {
e.printStackTrace();
}
if(Np!=0){
holder.offer(new OrdInt(j, Np));
}
j++;
}
return holder;
}
edit: by request, the code for power and matrix multiply.
public Matrix matrixMultiply(Matrix one) throws Exception{
if(this.size != one.size){
throw new Exception("Incompatible Matrices.");
}
Matrix total = new Matrix(this.size);
for(int x=0; x<this.size; x++){
for (int y=0; y<this.size; y++){
int hold=0;
for(int z=0; z<this.size; z++){
hold += this.get(x,z)*one.get(z,y);
}
total.set(x,y,hold%2);
}
}
return total;
}
public Matrix power(int power) {
Matrix holder = this;
if(power==0){
return identity(this.size);
}
if(power==1){
return this;
}
else{
for(int x=0; x<power; x++){
try {
holder =holder.matrixMultiply(this);
} catch (Exception e) {
e.printStackTrace();
}
}
return holder;
}
}

Why is my method behaving differently when called from different places?

I am making a graphical sudoku solver. Currently, I have a board where the user can enter the starting board configuration. Then they can click "solve" and it will solve the puzzle. To display the results, the method "displayResults()" is called:
void displayResult(int[][] boardArray) {
sudokuBoard.updateArray(boardArray);
sudokuPanel.repaint();
sudokuPanel.revalidate();
}
This then calls the updateArray() method:
void updateArray(int[][] boardArray) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(boardArray[i][j] == 0) sudokuArray[i][j] = "";
else sudokuArray[i][j] = Integer.toString(boardArray[i][j]);
squares[i][j].removeAll();
squares[i][j].add(new JLabel(sudokuArray[i][j], JLabel.CENTER));
squares[i][j].repaint();
squares[i][j].revalidate();
}
}
}
This works fine for "solve", displaying the results.
I have a menu bar in my program with an "open" item. This is meant to read in a text file (with an initial board configuration) and show the contents on the board.
I have tried calling the "displayResult()" method after reading in the file (passing in the resulting array). Unfortunately, nothing displays in the grid when it is called. Strangely, I have tried clicking solve, and the correct results will then appear in the grid.
sudokuPanel // the panel in the main window that contains the grid
sudokuBoard // an object of a Board class that contains all of the board info
squares // a 9x9 array of JPanels, representing the grid
sudokuArray // an array of Strings, containing the up to date information about the board configuration
I am having a similar problem with another method, however I am guessing that they are related. The read() method is:
protected void read() {
StringBuilder sb = new StringBuilder();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
chooser = new JFileChooser();
chooser.setFileFilter(filter);
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
File file = chooser.getSelectedFile();
Scanner input = new Scanner(file);
while(input.hasNext()) {
sb.append(input.nextLine());
sb.append("\n");
}
input.close();
readInToArray(sb);
} catch(FileNotFoundException e) {
System.err.println("File does not exist");
}
}
else return;
}
And readInToArray(), which calls displayResult():
private void readInToArray(StringBuilder sb) {
int[][] newArray = new int[9][9];
String[] lines = (sb.toString()).split("\n");
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
char c = lines[i].charAt(j);
newArray[i][j] = Character.getNumericValue(c);
}
}
if(!checkArray(newArray)) {
errorMessage("Incorrect configuration");
return;
}
displayResult(newArray);
}

I'm getting an IndexOutOfBoundsException with my arraylist, what am I doing wrong?

This class is in a program for a game I'm writing that is basically Space Invaders. I'm getting Exceptions for some reason and I don't see why I should be getting them.
Here's the class in question, but I can post all the code if necessary:
public class GamePanel extends JPanel {
Launcher launcher1;
Background bground1;
Shot shot;
public ArrayList<Shot> shots;
public int numShots;
public static int counter;
public GamePanel() throws IOException {
super();
this.shots = new ArrayList<>();
this.numShots = 0;
launcher1 = new Launcher();
bground1 = new Background();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bground1.background, 0, 0, getWidth(), getHeight(), null);
g.drawImage(launcher1.baldEagleImage, launcher1.getLxCoord(), launcher1.lyCoord, null);//paint the launcher
while (counter == 1) {
for (int i = 0; i < shots.size(); i++) {
g.drawImage(shots.get(i).mcDShotImage, shots.get(i).staticXLauncherCoord, shots.get(i).getSyCoord(), null);
}
}
}
public void move(GamePanel gamePanel) {
launcher1.moveX();
if (numShots > 0) {
moveShot();
}
repaint();
}
public void moveShot() {
for (int i = 0; i < numShots; i++) {//loop to move all the shots
if (shots.get(i).getSyCoord() > 10) { // THIS IS THE ISSUE, but I don't know why
counter = 1;
shots.get(i).moveY();
repaint();
} else {
counter = 0;
shots.remove(i);
repaint();
}
}
}
public void createShots() {
try {
for (int j = 0; j < numShots; j++) {
shots.add(new Shot());
}
} catch (IOException | IndexOutOfBoundsException e) {
System.out.println("caught an exception" + e);
}
}
}
The problem is in this piece of code:
} else {
counter = 0;
shots.remove(i);
repaint();
}
You remove an item from shots without adjusting numShots, causing an index out of bounds exception in one of subsequent iterations.
To fix this, either add numShots-- in the else branch, or use the built-in size() method that returns the count of elements in a list instead: unlike numShots which you need to maintain, shots.size() never gets "out of sync" with the actual count.
In the above line of code what is apparent is the issue is numShots is > shots.size() (because you also remove shots.
Since I couldn't where you are incrementing the numShots, in this piece of code one simple (albeit not sure from your logic perspective) change your for loop as below:
for (int i = 0; i < shots.size(); i++)

Java Applet Not Finding File [duplicate]

I have an applet that I am trying to make read a file. It throws an exception, but I am passing it the correct path so I am not sure where I am going wrong. I am using this to read numbers and use those numbers to change a multidimensional array, if you were wondering. Heres the code:
public class Save {
public void loadSave(File loadPath) {
try {
Scanner loadScanner = new Scanner(loadPath);
while(loadScanner.hasNext()){
for(int y = 0; y < Screen.room.block.length;y++){
for(int x = 0; x < Screen.room.block[0].length;x++){
Screen.room.block[y][x].groundID = loadScanner.nextInt();
System.out.println(loadScanner.nextInt());
}
}
for(int y = 0; y < Screen.room.block.length;y++){
for(int x = 0; x < Screen.room.block[0].length;x++){
Screen.room.block[y][x].airID = loadScanner.nextInt();
}
}
}
loadScanner.close();
} catch (Exception e) { e.printStackTrace();}
}
}
How I access it:
save.loadSave(new File(frame.getClass().getResource("mission1.tdm").toString()));
Ok, I used the edited code up above and it still says that it cannot find the file, even though the error spits out the exact path that it is in.

Categories

Resources