Printing individual parts of an array in a Java Gui app - java

OK, so I created a console app that, among other things, takes an array of numbers and prints them out one by one, line by line. Now, I have to take the class that I created for that console app, and pop it into a separate GUI app we're creating. I have all of the other methods working fine, but for the life of me I cannot get the array method to print out correctly. It just gives me the last number I typed into the text field. I'm hoping someone can give me a nudge to help me figure this part out so I can move along, and get to the whole SpringLayout stuff, (the main part of the new assignment) I am limited in what I can show you here because this is a current assignment, so I will have to stick to this stuff as specifically as I can. And please, don't just post the code as an answer, (because then I can't use it), thanks.
Here's what I had for my original project for the array method:
int [] getArray(int x)
{
breakUpNum(x);
return numAry;
}
From there, inside my new class I have this, in an attempt to get it to print:
private class ButtonTest implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Lab1 tester = new Lab1();
int[] test4 = tester.getArray(num);
for(int i = 0; i < test4.length; i ++)
{
crossTest.getArrCross.setText("" + test4[i]);
}
}
}
Any help pointing me in the right direction would be greatly appreciated, thanks!

setText does just that, sets the text you pass to as the current text content, it does not append it.
If you were to use JTextArea, you could use it's append method...however, for a JTextField you need to have a different approach.
Now you could use getArrCross.setText(getArrCross.getText() + test4[i])...but to quite frank, that's rather inefficient, as each call to setText is going to stage a paint event...
StringBuilder sb = new StringBuilder(128);
for(int i = 0; i < test4.length; i ++)
{
sb.append(test4[i]);
}
crossTest.getArrCross.setText(sb.toString());
Now, if you want to separate each element, you need to add
if (sb.length() > 0) {
sb.append(", ");
}
Before sb.append(test4[i]);

The last bit of actionPerformed in the for loop isn't working right. setText replaces the current text with its argument, and it doesn't seem like you want to do that. To fix it, replace the line in the for loop with this:
crossTest.getArrCross.setText(crossTest.getArrCross.getText() + test4[i]);

Related

How can I repeat a method with a variable integer?

I just started learning how to program in Java a month ago. I am trying to make my robot (karel) put a beeper the amount of times that is indicated in the "put" integer only, not the total amount the object has. However, it is not a set number and karel.putBeeper(put); does not get accepted in the compiler due to the class not being applied to given types. Any help would be greatly appreciated, and I am starting to understand why Stack Overflow is a programmer's best friend lol. Note: I might not respond to to any helpful tips until tomorrow.
import java.io.*;
import java.util.*;
public class Lab09 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("Which world?");
String filename = input.nextLine();
World.readWorld(filename);
World.setSize(10,10);
World.setSpeed(6);
Robot karel = new Robot(1,1,World.EAST,0);
int pick=0;
int put=0;
for(int i=0; i<8; i++) {
while(karel.onABeeper()) {
karel.pickBeeper();
pick++;
karel.move();
}
for(i=0; pick>i; pick--) {
put++;
}
if(!karel.onABeeper()) {
karel.move();
}
while(karel.onABeeper() && put>0) {
karel.putBeeper(put);
}
}
}
}
If I got your question right, you're trying to putBeeper put times, which is done by the following code:
while (karel.onABeeper() && put > 0) {
karel.putBeeper(put);
}
The issue I see here is that you're not changing the value of put after calls to putBeeper, hence this while loop will never terminate: for instance, if the value of put was 5 during the first loop iteration, it will always remain 5, which is larger than 0. Also, as you've mentioned, putBeeper doesn't take any arguments, hence trying to pass put as an argument won't work - the compiler catches that error for you.
If your intent is to call putBeeper put times then what you can do is decrement put after every invocation of putBeeper - put will eventually reach 0, at which point you've called putBeeper exactly put times. And since you're just learn to program in Java, I'll leave the actual implementation to you as an exercise. Good luck!

Java use a piece of code from a text file

I am currently trying to figure something out. For my world editor I want my program to read a text file and use its content as code material. I've already made a decent file reader but now I've got a problem. In the console I am getting the right output, the file has only one line that says:
this.makeGrass(new Vector3f(0, 1, 2));
this is actually part of a code that tells my program to render a specific object to the scene, in this case it's a grass model. However instead of just printing this information to the console with
System.out.println(aryLines[i]);
I want to be able to use the information stored on the .txt file so I can actually add it to my rendering code. The entire method that prints the lines on the text file to the console is:
public void TextOutput()
{
String file_name = "C:/Text.txt";
try
{
StoreCoords file = new StoreCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
// !! How to use the information as part of my code ??
}
} catch(IOException e)
{
System.out.println(e.getMessage());
}
}
I hope you understand what I want: The content of my text file is a piece of code that I want to use further instead of having it just print to the console, I'm sure this is possible but I wouldn' know how.
As Java is a compiled language, you'd have to recompile at runtime and I am not sure that is even possible. If I were you, I'd hardcode in my own commands. You want to call a function called makeGrass, hardcode it in. Maybe in your text file you can have this:
makeGrass:0,1,2
Then have this right after the println:
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
ArgArray = Arguments.split(",");
this.makeGrass(new Vector3f(Double.parseDouble(ArgArray[0]), Double.parseDouble(ArgArray[1]), Double.parseDouble(ArgArray[2])));
}
I'm going to leave my answer like this, assuming you are an experienced programmer. If I am wrong feel free to ask and I will explain it to you. I can also explain how to modify it to add different commands if you want.
Also, this is rather unsafe because if the input is in the wrong format it will crash the app. If you plan on letting users edit the file, then I can show you how to add on safeties.
Hope this helped,
Joseph Meadows
Okay, thanks to Joseph Meadows for the hint, I'm doing the following thing, right after the println statement I've added the code provided by him. To make ArgArray work I had to put String[] before it and also I had to create a new constructor in my Vector3f class to match the Double.parseDouble thingy..
public void TextOutput()
{
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
StoreCoords file = new StoreCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
String[] ArgArray = Arguments.split(",");
this.makeGrass(new Vector3f(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2])));
}
}
} catch(IOException e)
{
System.out.println(e.getMessage());
}
}
my original Vector3f constructor is:
public Vector3f(float x, float y, float z)
{
this.m_x = x;
this.m_y = y;
this.m_z = z;
}
and to make the code in the TextOutput method work I've added another constructor right below the original one..
public Vector3f(double parseDouble, double parseDouble2, double parseDouble3) {
this.m_x = (float) parseDouble;
this.m_y = (float) parseDouble2;
this.m_z = (float) parseDouble3;
}
Now everything works great, the console gives me the apropriate statement
makeGrass:0,1,2
and the rendering system creates the grass model at the apropriate coordinates, the only thing I want to change now is that I don't have to add an additional constructor to the Vector3f class, I'm sure I'll figure that out too.
In the picture provided in this link you can see exactly what's going on:
http://www.pic-upload.de/view-27720774/makeGrassEx.png.html
As you can see, the content of the text file is printed out in the console (the numbers below is the fps counter) and the coordinates provided by the text file are interpreted correctly, two grass models being displayed at the respective coordinates which is exactly what I wanted!
Thanks again for your help Joseph Meadows, this is exactly what I was looking for!
I am not sure if you solved this yet, but you did not need the second constructor. I was unsure of the data type you were using for the coordinates, and I assumed you use doubles because that is what I have grown accustomed to using.
In actuality, all types can be parsed from a string. Look here:
this.makeGrass(new Vector3f(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2])));
This right now is turning the string into a double. That is what
Double.parseDouble();
does.
It looks like you are using floats though, so you can always just use the float parsing method:
Float.parseFloat("String");
That would result with this:
this.makeGrass(new Vector3f(Float.parseFloat(ArgArray[0]),
Float.parseFloat(ArgArray[1]),
Float.parseFloat(ArgArray[2])));
Sorry for the late response, and you are surely welcome for the help. I just love being useful!

Java program won't finish method - exits after a for loop with no errors instead

edit: As I was writing this post, I made my code simpler (lost arrays entirely) and got it working. Yet I am still not sure why this specific code won't work, so I'll keep the question.
Hello.
I am writing a small puzzle game in Java (using Eclipse 4.4.2) and stumbled upon a problem inside one of my methods. Basically - it won't complete the method, it just exits the method after the for loop is done without any warnings or errors (I'm not catching exceptions either). I hope I missed something simple..
Details:
I have a method to set the colors of an object and up to 5 other objects that are linked to it through lines. I set up the color of the main object, then find the linked objects through for-loops and in the end change their colors as well. (Double checked the code for Lines, there are simple return methods and nestA and nestB as data - no problem there). lines is an array with a length of 50, nests as its members.
Here's the code:
public void highlightNests(Nest nest) {
//setting the color of the main object (a nest).
Mappers.setColor(nest, nestHighlight);
//resetting the array. Temp solution, had a return method earlier,
//this is part of the debugging.
connectedNests = null;
connectedNests = new Nest[5];
int i = 0;
Gdx.app.log("highlightNests()", "starting the loop");
for (int j=0; j<lines.length; j++) {
if (lines[j].getNestA() == nest) {
connectedNests[i] = lines[j].getNestB();
i++;
}
if (lines[j].getNestB() == nest) {
connectedNests[i] = lines[j].getNestA();
i++;
}
}
//This is where the program exits the method. The following
//lines are not run.
Gdx.app.log("highlightNests()", "entering loop");
for (int l=0; i<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
}
Deleting the middle section makes the end part run, so there are no errors in the last part.
Your second loop is completely wrong, you declare the counter as l and increment another counter i, you should use l<connectedNests.length change it like this:
for (int l=0; l<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
And the program won't finish method and exits before the loop because, it doesn't even enter the loop as it's incorrect.
You have to use l instead of i in condition like,
for (int l=0; l<connectedNests.length; l++)...
//---------^ l not i

Java update jLabel.setText via for loop

I basically checked out a book from the Library and started learning Java. I'm trying to code a little score calculator for my golf league and this site has been a lof of help! So thanks for even being here!
Now to the question:
I have a 9 labels, created with NetBeans GUI, with names like jLabel_Hole1, jLabel_Hole2, ...
If a user selects the radio option to play the front nine those labels have number 1 - 9 and if they change it to the "Back Nine" then they should display 10 - 18. I can manually set each label to the new value on a selection change but I wanted to know if there was a more elegant way and if so if one of you could be kind enough to explain how it works.
Here is the code that I want to try and truncate:
TGL.jLbl_Hole1.setText("10");
TGL.jLbl_Hole2.setText("11");
TGL.jLbl_Hole3.setText("12");
TGL.jLbl_Hole4.setText("13");
TGL.jLbl_Hole5.setText("14");
TGL.jLbl_Hole6.setText("15");
TGL.jLbl_Hole7.setText("16");
TGL.jLbl_Hole8.setText("17");
TGL.jLbl_Hole9.setText("18");
I've read some things about String being immutable and maybe it's just a limitation but I would think there has to be way and I just can't imagine it.
Thanks.
Basically, rather then creating a individual label for each hole, you should create an array of labels, where each element in the array represents a individual hole.
So instead of...
TGL.jLbl_Hole1.setText("10");
TGL.jLbl_Hole2.setText("11");
TGL.jLbl_Hole3.setText("12");
TGL.jLbl_Hole4.setText("13");
TGL.jLbl_Hole5.setText("14");
TGL.jLbl_Hole6.setText("15");
TGL.jLbl_Hole7.setText("16");
TGL.jLbl_Hole8.setText("17");
TGL.jLbl_Hole9.setText("18");
You would have...
for (JLabel label : TGL.holeLables) {
lable.setText(...);
}
A better solution would be to hide the labels from the developer and simply provide a setter...
TGL.setHoleText(hole, text); // hole is int and text is String
Internally to your TGL class, you have two choices...
If you've used the form editor in Netbeans, you're going to have to place the components that Netbeans creates into your own array...
private JLabel[] holes;
//...//
// Some where after initComponents is called...
holes = new JLabel[9];
holes[0] = jLbl_Hole1;
// There other 8 holes...
Then you would simply provide a setter and getter methods that can update or return the value...
public void setHole(int hole, String text) {
if (hole >= 0 && hole < holes.length) {
holes[hole].setText(text);
}
}
public String getHole() {
String text = null;
if (hole >= 0 && hole < holes.length) {
text = holes[hole].getText();
}
return text;
}
Take a closer look at the Arrays tutorial for more details...
I've never found a Java GUI-generator to provide code that's any good. I may be wrong--there may be a good one, but I always prefer to position and name them myself. So,
/**
* The JLabels for the holes on the golf course.
* <p>
* holeLabels[0][i] are for the outward holes, 1-9.
* holeLabels[1][i] are for the inward holes, 10-18.
*/
private JLabel[][] holeLabels;
/**
* The starts of the outward and inward ranges of holes.
*/
private static final int[] holeStart = {1, 10};
// Later
holeLabels = new JLabel[2][9];
for(final int i = 0; i < holeLabels.length; i++) {
for (final int j = 0; j < holeLabels[i].length; j++) {
holeLabel[i][j] = new JLabel();
holeLabel[i][j].setText(Integer.toString(holeStart[i] + j));
}
}
Interestingly, holeLabels.length is 2. holeLabels is an array of 2 arrays of 9 ints. i goes from 0 to 1, and j goes from 0 to 8, so the text computation works. The reason I did things this way is so you can easily place the labels in an appropriate GridLayout later.

How to make a method to move a character in an array?

here's the deal, I have to make a game that resembles PacMan, with a map, points, ghosts, etc.
The whole thing works as an array[8][8], it reads the positions of walls and the initial position of ghosts from a .txt file, PacMan starts at a fixed location and Fruits are random. Any blank space at the beginning of the game gets filled with a simple point pellet.
I've got the map done, it shows it and everything, but I can't seem to come up with a method that allows the player to control PacMan with the keyboard... This is what I've tried so far...
In the Player class
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String mov = read.readLine();
if (mov.equals("w"))
{
PacMan.MoveU();
}
It then repeats that for the other movement keys.
The individual Move methods in PacMan class look like this
public static void MoverR()
{
for (int i=0;i<Tablero.length;i++)
{
for (int j=0;j<Tablero.length;j++)
{
if (Tablero[i][j] instanceof PacMan)
Tablero[i][j]=null;
Tablero[i][j+1]=new PacMan();
}
}
}
}
This obviously isn't working, so I'm wondering if anyone can help me with a more efficient way to do this? I really don't mind starting these two classes from scratch...
Thanks.
It always gives me an ArrayOutOfBounds Exception
The ArrayOutOfBounds Exception is caused by Tablero[i][j+1]=new PacMan(); when j == 7, because you try to access to an invalid position (Tablero[i][8]).
anyone can help me with a more efficient way to do this?
You don't need to check the whole array to find out the position of Pacman, you could store the position as a private variable of Pacman, but in that case you shouldn't create a new instance of Pacman every time you need to move it, like you are doing with your current implementation.
One reason why you get ArrayOutOfBoundsException is the fact that in your loop you're moving PacMan to position [i][j +1], where j + 1 may be greater than array length.
You need to check if j + 1 < Tablero.length when you're 'moving' PacMan.
Also you can simply move the same instance of PacMan instead of creating a new one:
...
if (Tablero[i][j] instanceof PacMan) {
if (j + 1 < Tablero.length) {
Tablero[i][j+1] = Tablero[i][j];
Tablero[i][j] = null;
}
}

Categories