Loop through column of tableview and get cell data - java

I have a TableView with two Columns (let's call them A and B). I like to loop through column A and print their values to console. My code doesn't seem to work the way I want it to....
for (int i : myTable.getItems().size()) {
System.out.print(columnA.getCellData(i));
}
Suggestions?

You almost had it! But I don't think that for loop is valid - it expects an Array not an int.
for (Object o : myTable.getItems()) {
System.err.println(columnA.getCellData(o));
}
Or if you are using Java 8, this is a shorter way:
myTable.getItems().stream().forEach((o)
-> System.err.println(columnA.getCellData(o)));
This works for me.
If it doesn't just comment and I'll see what's wrong.

I just checked the code and found a small correction - the type of the item for getCellData() must be String not object. For the first example, this would result in:
for (String[] o : myTable.getItems()) {
System.err.println(columnA.getCellData(o));
}

Related

Conditional and iterators in ruby

I'm trying to translate the following code into ruby:
public void discardWeapon(Weapon w){
if(!weapons.isEmpty()){
boolean discarded = false;
Iterator<WeaponType> it = weapons.iterator();
while(it.hasNext() && !discarded){
WeaponType wtaux = it.next();
if(wtaux == w.getWeaponType()){
it.remove();
discarded = true;
}
}
}
}
But, when it comes to the while loop, I can't really find a practical way to do it in ruby. I've got the following structure so far:
def discardWeapon(w)
if(!#weapons.empty?)
discarded = false
#weapons.each do |wtaux|
end
end
end
But, how can I check my condition is met when using the .each iterator?
Thanks in advance.
I am not sure if I read your Java code correctly, but it feels to me like you have an instance variable #weapons that holds an array of weapons and you want to discard one instance of a weapon w from that list.
def discard_weapon(weapon)
index = #weapons.index(weapon)
#weapons.delete_at(index) if index
end
Array#index returns the index of the first match. And Array#delete_at deletes the element at the index when there was an element found.
When it is possible that the same weapon is included in the array multiple times and you want to discard all matching weapons then you can use the following one-liner:
def discard_weapon(weapon)
#weapons.delete(weapon)
end

Method to check if label is empty is not working

I am working on a program which uses jLabels and I need to check if label is empty or not. If it's empty it should just pop up a note that it's empty and nothing else, but it actually throws a lot of errors. I'm using label.getText().isEmpty().
Here's the code:
if(Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||najboljsi1.getText().isEmpty()||
Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najboljsi2.getText().isEmpty()||
Integer.parseInt(najboljsi3.getText())<1||Integer.parseInt(najboljsi3.getText())>17||najboljsi3.getText().isEmpty()||
Integer.parseInt(najslabsi1.getText())<1||Integer.parseInt(najslabsi1.getText())>17||najslabsi1.getText().isEmpty()||
Integer.parseInt(najslabsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najslabsi2.getText().isEmpty()||
Integer.parseInt(najslabsi3.getText())<1||Integer.parseInt(najslabsi3.getText())>17||najslabsi3.getText().isEmpty())
{
jLabel101.setForeground(Color.red);
jLabel101.setText("Eno ali več vnesenih števil ni v pravilnem obsegu (1-16)!");
}
else
{
jLabel101.setText("");
int a=Integer.parseInt(najboljsi1.getText());
tabela[a-1]+=3;
int b=Integer.parseInt(najboljsi2.getText());
tabela[b-1]+=2;
int c=Integer.parseInt(najboljsi3.getText());
tabela[c-1]+=1;
int d=Integer.parseInt(najslabsi1.getText());
tabela[d-1]-=3;
int e=Integer.parseInt(najslabsi2.getText());
tabela[e-1]-=2;
int f=Integer.parseInt(najslabsi3.getText());
tabela[f-1]-=1;
najboljsi1.setText("");
najboljsi2.setText("");
najboljsi3.setText("");
najslabsi1.setText("");
najslabsi2.setText("");
najslabsi3.setText("");
count++;
jLabel1.setText("Učenec "+count);
}
Everything else in if statement works ok, if value is lower than 1 or higher than 16, it throws a pop up.
Yes, you must test najboljsi1.getText().isEmpty() BEFORE any parsing of najboljsi1.getText().
Your if would become:
if(najboljsi1.getText().isEmpty()||Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||
najboljsi2.getText().isEmpty()||Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||
etc...
If you do Integer.parseInt(najboljsi2.getText()) on a label with the textn "" (empty String), it won't be an integer. An exception will be thrown.
I think your problem is in the use of the "Integer.parseInt" without any check! If, for example, the variable contains an empty string, it will throw an Exception and your if clause will never work!
I would manage the situation with a double check.
Check if it is already a number (this guide could help
check-if-variable-is-a-number-in-javascript)
Then, if it is a string, check if it is empty and if it actually contains a string (the following post could also help check-whether-an-input-string-contains-a-number-in-javascript)
Ps. Sorry, I modified the answer with some extra links

Java: showing the output of a separate for loop as an extra column shown in a console

Bit of context...
In my project I have one embedded for loop that outputs data whereby for each category show the item and within each item show its property so in reality the output I generated is 3 columns of data in the console (headings: Category/Item/Property) The for loop to show this data looks like this (Variables are set earlier on in the method):
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
out.println(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
The purpose of the project is to provide a more dynamic documentation of the properties of set components in the system. (The /t making it possible to separate them in to individual columns on a console and even in a file in say an excel spreadsheet should I choose to set the file on the printstream (Also at the start of this method.))
The Problem
Now for the problem, after the for loops specified above I have generated another for loop separate from the data but shows the list of all the functions and operators involved in the components:
//Outside the previous for loops
for (Function function : Functions.allFunctions) {
out.println(function.getSignature());
}
What I want is to set this list as the 4th column but the positioning of the for loop and the way it is set leaves it fixed on the first column with the categories. I cant add it after property names as the functions are more generic to everything in the lists and there maybe repetitions of the functions which I am trying to avoid. Is there a way to set it as the forth column? Having trouble finding the sufficient research that specifies what I am looking for here. Hope this makes sense.
One solution, if the total amount of output is small enough to fit in memory, is to simply save all the data into an ArrayList of String, and output it all at the very end.
List<String> myList = new ArrayList<String>();
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
myList.add(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
int i = 0;
// Here we assume that the total lines output by the previous set of loops is
// equal to the total output by this loop.
for (Function function : Functions.allFunctions) {
out.println(myList.get(i) + "\t" + function.getSignature());
i++;
}

Multiple JList selected indexes breaking each other

I have a simple interface that is designed to select one or more seats in a theater and reserve them for yourself.
I have three columns: zone / row / seat. You select the first to populate the second, and the second to populate the third.
When I select them the first time no problem.
If I change the second row, the third row re-populates (in this case all rows have the same number of seats) it does not break!
However if I change the first row everything breaks!
Now the reason for this is kinda clear, but I don't understand exactly why this is.
This is the first list event trigger:
List_Zona.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
if (! arg0.getValueIsAdjusting()){
RowListModel.clear(); // second list
SeatListModel.clear(); // third list
List_Rand.clearSelection(); // second list
List_Scaun.clearSelection(); // third list
int[] rows = self.repository.getRowsForZone(
List_Zona.getSelectedValue().toString()
);
int index = 0;
while (rows[index]!=0) {
RowListModel.addElement(String.valueOf(rows[index]));
index++;
}
}
}
});
It should clear the other column selections so it should not interfere with this next trigger (second column), but apparently it does, or something happens which I don't get:
List_Rand.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
if (! arg0.getValueIsAdjusting()){
SeatListModel.clear();
int[] seats = self.repository.getSeatByZoneAndRow(
List_Zona.getSelectedValue().toString(),
Integer.parseInt(List_Rand.getSelectedValue().toString())//HERE
);
int index = 0;
while (seats[index]!=0) {
SeatListModel.addElement(String.valueOf(seats[index]));
index++;
}
}
}
});
It can't parse the integer because the second column should be cleared, but it's not ? But even though it's not ... it is ?
What I'm trying to say: The second column should be clear (it's not) but if it's not then the error should not occur, but it does.
I hope this makes some sense!
Can anyone spot the problem ? Should I provide more code ?
The error is a NullPointerException at the second column, because something fishy is happening there (again: at the integer parsing).
By my mind the second column's valueChanged should not trigger at all when I click an item in the first column. It should just clear the other two and that's that. Why am I wrong ?
P.S. First Code snippet is responsible for the second one breaking the program.
Maybe I should also rephrase the question How can I safely clear everything when I re-select a new "Zone" (Zona) - Column one ?
The first listener clears the selection of List_Rand. That makes the selection change: it goes from "the index i is selected" to "no index is selected", so the second listener is invoked. And in the second listener, you're trying to call a method on the selected value of List_Rand. Since you just cleared the selection, there's no selected value anymore, hence the NullPointerException.
Side note: your code is very hard to read, because it doesn't respect the Java naming conventions. Variables start with a lowercase letter, and are camelCased (no underscore in their name).
Other side note : what's the point in calling parseInt(selectedValue.toString())? If the list contains Integer instances, the cast the value to Integer directly. If it contains String, then why not store Integers instead, since this is what you want the list to contain?

How shall I execute an ArrayList program with a loop that renders each index of the list one at a time?

How shall I execute a program where as long as the array/list [idk which one to use yet but I've been told that with ArrayList I don't have to predefine a size so I'll use that] it will keep looping and the values are observed or rendered one at a time?
I've tried using the while loop but basically all I got were errors asking for an array or saying incompatible types or something like that.
while (myList!=0) //Can I actually do this? Because I didn't define a data type for my list.
if myList(0).equals ("A") //problem here is that I need to go through every index of the list. I've tried to use a counter like if myList(counter).equals ("A") but it says its incompatible types?
{
//print something.
} else if myList(0).equals ("B")
{
//print something
}
I know the question is kinda confusing but the code [even if it's full of errors] is exactly what I want to do. I just don't know how to apply it. Any help, answers, links, articles, tutorials would be reaaaaly appreciated.
Looks like you're thinking of it in terms of a C pointer. The List always points to a List, never to a Node or anything like that. So you'd do something like this intsead:
for(String s : myList) {
if("A".equals(s)) {
} else if("B".equals(s)) {
}
}
If you're using an ArrayList or some other implementation of the List interface you aren't going to have direct access to the data using brackets or parentheses, meaning that saying something like myList[0] is meaningless. Instead, what you are going to want to do is use the get method and then compare it to whatever values you need. You will be able to get the length of your List by using the .size() method, so your code will look something like this
for(int i=0; i<myList.size(); i++)
{
if(myList.get(i).equals("A"))
{
//print something
}
else if(myList.get(i).equals("B"))
{
//print something else
}
else
{
//print something still different
}
}
The response that glowcoder gave is a more compact syntax for looping over ArrayLists and other Lists in Java and results in nicer code, but this is how you'd do it sans syntactic sugar.
Is this answer suitable for your question?
for (int i = 0; i < myList.length; i++) {
if ("A".equals(myList[i])) {
// print something.
} else if ("B".equals(myList[i])) {
// print something
}
}
This should be working and quite close to what you tried so far:
int counter = 0;
while(counter < myList.size()) {
if (myList.get(counter).equals("A") )
{
//print something.
} else if (myList.get(counter).equals("B"))
{
//print something
}
counter = counter + 1;
}
Note that this is not the preferred way of looping over a list, see glowcoder's answer for something more elegant.

Categories

Resources