I'm trying to display the contents of an ordered array in something like a JTextField.
for (int i=0; i<array.length; i++) {
this.textField.setText(array[i]);
}
This won't work for two reasons. The first minor reason: if the array length is 4 then jtextfield is getting it's value reset 4 times rather than appending each element onto the last.
Second reason: The JTextField only takes strings. I can't find anything I can use in Swing that will let me display integers to the user. Any help?
Quick & Dirty Answer
for (int i=0; i<array.length; i++) {
this.myJTextField.setText(this.myJTextField.getText() + ", " + array[i]);
}
Correct Way
First, calling a member variable JTextField probably isn't wise. Since the class is already called like that, it will confuse readers. Naming conventions in Java state member variables are like myTextField for example. (note: original question changed).
User defined format
Note you can convert any number to a string by simply doing "" + number too. If you have many strings, consider using a string builder, as that's faster and won't update the GUI element multiple times: (also fixes the initial ", " before the first item, which happens above)
StringBuilder builder = new StringBuilder();
for (int i=0; i<array.length; i++) {
builder.append(array[i]));
if(i + 1 != array.length)
builder.append(", ");
}
this.myJTextField.setText(builder.toString());
Canonical array representation
Alternatively, you can use this:
this.myJTextField.setText(Arrays.toString(array));
It will look like [1, 4, 5, 6].
You can concatenate all those integers into a string the then present that value in the textfield.
StringBuilder sb = new StringBuilder();
for( int i : array ) { // <-- alternative way to iterate the array
sb.append( i );
sb.append( ", " );
}
sb.delete(sb.length()-2, sb.length()-1); // trim the extra ","
textField.setText( sb.toString() );
You can use a JTextArea instead of the textfield too.
Related
This question already has answers here:
Java: join array of primitives with separator
(9 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I'm creating a class with a char[] array as the only instance variable. I have to use a constructor and accesor methods and such but the difficult part is creating an efficient toString() method.
Right now, I've initialized the array as:
private char[] tune = new char[5];
My toString() method looks like this:
public String toString() {
return notes[0] + " " + notes[1] + " " + notes[2] + " " + notes[3] + " " + notes[4];
}
My question is: Is there a more efficient method of printing this. I thought of using a for loop, as shown below:
for(int i = 0; i <= tune.length; i++) {
return tune[i] + " ";
}
but I assume that would return tune[0] and just stop.
If you want to override the toString() method, use a StringBuilder which is initialized outside the loop.
public String toString() {
StringBuilder sb = new StringBuilder();
for (char ch : array) { // you used both notes and tune arrays in your examples,
// so I'm just going to use "array" as the variable name as an example
sb.append(ch);
sb.append(" ");
}
return sb.toString();
}
Note that this will cause an extra space at the end, if this is not wanted, use this instead:
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length - 1; i++) { // adds a space after every element
// except for the last one, hence "i < array.length - 1"
sb.append(array[i] + " ");
}
sb.append(array[array.length - 1]); // adds only the last element and no space
// after
return sb.toString();
}
Hope this is easy to understand!
NOTE - Java can already convert the char[] to string, but I'm assuming you want to change the way it does that.
Arrays already have built in methods to print out the entire Array. (Not the case for ArrayLists).
If you look in the documentation for Arrays, you can see that there is a function called Arrays.toString()
Here is an example of how you can use it.
String[] array = new String[] {"a","b","c"};
// Print out the Array
System.out.println(Arrays.toString(array));
// Output
[a,b,c]
If you would like to print out an array from index a to index b, then using a for... loop would be better.
I've read in other posts, that instead of writing just System.out.println(finalPressedKey);
you should write System.out.println(Arrays.toString((finalPressedKey)); because otherwise it will just return the location where the String is saved (as far as I understood it).
public static String PressedKey[] = new String[2000];
public static String[][] finalPressedKey = {{ "", "", "", "", "", "", "", "", "", "", "", "" }}; // 12
public static String FPK3;
public static void upcounter(KeyEvent e) {
for (int x = 0; x < PressedKey.length; x++) {
if (PressedKey[x] != null && PressedKey[x + counter] != null) {
//FPK counter is supposed to be a line, and counter is where the words are supposed to be saved
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
System.out.println(Arrays.toString(finalPressedKey));
}
}
Whenever I Press a Button, it should be saved in my PressedKey Array, and finalPressedKey is supposed to contain itself, and PressedKey (also , only the last element of the array is supposed to be printed), but instead it just prints [[Ljava.lang.String;#76f42c4b]
I also tried using Arrays.deepToString(); but it gives me the same output as with Arrays.toString();
Thanks for your help!
A String[][] is not a 2-d array. It is an array of String[]. The difference is subtle but important.
The method Arrays.toString() takes an array, iterates through its elements, calls toString() on all of them, and adds a prefix, suffix, and delimiters. Since you give it a String[][] (an array of String[]), it will do the following:
Iterate through the elements (each of them a String[])
call toString() on each element - giving the default toString() value of an array - i.e. its memory address (not really but for this purpose it doesn't matter)
concatenate
Luckily for you, there is an easier way - just use Arrays.deepToString(). This behaves as you would expect.
I did not understand the whole code, but following statement is very suspicious:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
since it is adding an array (finalPressedKey[...]) to a string (PressedKey[...]), which will result in that strange text - the standard textual representation of an array (returned by toString). (from a mathematical point of view, it's strange to have 2 indexes )2D_ before the assignment and only one on the right side (1D) for same matrix)
I'm not sure, since we cannot see what counteris, but I believe you wanted something like:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter][counter] + PressedKey[x + counter];
that is, an additional [counter] on second line.
This can also be written as
finalPressedKey[FPKcounter][counter] += PressedKey[x + counter];
If you only want to store lines of strings, a normal String[] is good for you
finalPressedKey[FPKcounter] += PressedKey[x + counter];
even though I wouldn't recomment doing this, no matter what you're trying to accomplish, since this will create a new String object each time a key is pressed.
Maybe ask the question differently and tell us what you're trying to do. I guess String arrays might not be the way to go.
You have to print the elements of your array with
for(int i = 0; i<finalPressedKey[0].length; i++){
for(int j=0; j<finalPressedKey[1].length; j++){
System.out.println(finalPressedKey[i][j]);
}
}
if I understand it correctly.
I am learning Java and I would like to know how you can print an array in a pop-up Box using JOptionPane?
I don't mean printing them in separate boxes for each element of the array but printing the whole array content in a single box with JOptionPane.showMessageDialog, after having input the values one by one by JOptionPane.showInputDialog.
Example:
Write a program that inputs 5 Integers (or strings) and store them in an array. It then print the array in a pop-up box at the end, with all the variable values.
Basically, this is how I'd start:
int numberBox[] = new int[5];
for (int i = i; i<numberBox.lenght; i++)
{
String text = JOptionPane.showMessageDialog (null, "Give me numbers:");
numberBox[i] = Integer.parseInt (text);
}
Actually, the code I have written I am sure it has mistakes. Then again, that is why I need your help.
Once you have gathered input and built an array of ints or Strings, here's how you can print them in a dialog box:
// Get the input; this could be an array of ints or strings, either will work
int numberBox[] = gatherInput();
// Convert the array into a String form: "[1, 2, 3, 4, 5]"
final String numbers = Arrays.toString( numberBox );
// And show a simple dialog box with the numbers
JOptionPane.showMessageDialog( null, numbers );
For gathering user input: Getting the User's Input from a Dialog
You need to build a string that contains entered numbers separated by delimiter. To build a String take a look at StringBuilder. This class is mutable, it means that new object won't be created every time you add something to the string. To compare with, String is immutable and not efficient if you're going to concatenate several elements.
It's also possible to use Arrays Java class, but I would recommend to look at StringBuilder also to extend your knowledge.
you could try something like this
int[] array = {1,2,3,4,5};
String end = "";
for(int i = 0; i < array.length; i++){
end += array[i] + " ";
}
JOptionPane.showMessageDialog(new JFrame(), end);
Sometimes, due to faulty data collected, a line generated by the following method ends up looking like this when saved: ",-1,0" or something similar, with no name, an ID of -1 and a level of 115 or something else. (The lines are formatted like this (excluding quotes): "name,id,level" (e.g: "Honour guard,5514,115")
What i need to do is to remove all strings in monstersToAdd that contains -1.
I've tried this, but with no success:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
monstersToAdd.remove(monstersToAdd.contains("-1"));
}
with the line monstersToAdd.remove(monstersToAdd.contains("-1")); I was trying to remove all strings in monstersToAdd that contains "-1". This however does not work, probably for good reasons, which I unfortunately don't know of yet.
I would really appreciate any input :).
You would be better off not adding the lines you don't want in the first place.
for (....) {
if (IDs[i] != -1) {
// add it
}
// else it simply doesn't get added
}
More on your original code: You could post a little more detail, such as the type of monsterToAdd. If it is a non-generic list, then the contains method just returns true or false depending if the parameter (here a string of "-1") is present in the list exactly as you pass it, that is it doesn't search for substring matches of the list elements.
remove then tries to remove the element you ask to remove, which may be a Boolean object, automatically boxed from the boolean primitive value returned by contains.
Also, it is suspicious that you have a variable called monsterList which you use for iteration length, but not actually use any elements from that list. Maybe the arrays you use have the same values as the list, and were copied out beforehand? If so, it would be nicer to iterate on the monsterList directly and use its elements.
Its easier if you dont even add them, than adding and removing them so check the sanity of ID names and levels before adding them
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
//add only if name is non empty, ID is not negative and level is below 100
if(!(names[i].isEmpty() || IDs[i]<0 || levels[i]>100))
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
Why don't you do this instead:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
if(IDs[i] != -1){
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
}
monstersToAdd.remove(monstersToAdd.contains("-1"));
}
That way, you never add the monster to the list in the first place, if the ID is -1.
You are really close:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
if (IDs[i] == -1) continue; // Skip this iteration
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
}
Filter them out as early as possible rather than back-tracking and removing them.
contains() returns only a true/false result depending on whether the list contains the given input object (in your case the string "-1"). So in your example, your list wouldn't contain "-1", so your remove statement would be resolved to this:
monstersToAdd.remove(false);
which wouldn't work for obvious reasons.
Here is the code:
for(Iterator<String> it = monsterList; it.hasNext();) {
String elem = it.next();
if (elem.contains("-1")) {
it.remove();
}
}
contains() method of collection returns true if collection contains element equals to one passed as an argument. In you case you want to use String's contains() that returns true if the string contains specified substring. This is the reason that you need loop.
This loop must be implemented with iterator. Using new java 5 syntax for(String elem : list) will not work here because you have to remove element. Using for(int i = 0; i < list.size(); i++) requires implementation of logic that safely moves to the next index after element removal.
And the last point. You have to use iterator.remove() instead of Collection.remove() to avoid ConcurrentModificationException
if i was using a JOptionPane message dialog box how would I be able to show an the whole array in the message section such as this little snipit? or would that evenbe possible?
public void showTheMessage()
{
JOptionPane.showMessageDialog(null,"These are are all the colors to
choosfrom,\n"+ arrayOfcolors[the whole array], "Color box");
}
The easiest thing to do would be to concatenate all the elements of the array into one big string.
String colors = "";
for(int i = 0; i < arrayOfColors.length; i++)
colors += arrayOfColors[i] + " ";
The showOptionDialog method lets the user select a single element from an array of options, which I think is what you're looking for.
In case its an array of Color objects
String colors="";
for (Color c: arrayOfColors)
colors+= c.toString() + " ";
Otherwise if its an array of String objects
String colors="";
for (String s: arrayOfColors)
colors+= s + " ";
Just a note, using StringBuilder is much faster, but this is just a small array i guess.