开发者

Counter of lines in JTable

In the following code, I browse a table and count lines containing "ble", "cle", "tion"; my counters print the expected values at x=1, but at x=2 and 3 the value of counters is wrong.

I'm working with JTable and trying to count on each value of x the number of lines containing the above strings.

Expected values:

x=1: counter1=5 counter2=5 counter3=6

x=2: counter1=10 counter2=10 counter3=6

x=3: counter1=20 counter2=17 counter3=6

int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
for (int x = 1; x < 4; x++)
{
  myTable.goToValue(x);               
  for (int i = 0; i < myTable.getRowCount(); i++)
  {    
    if (myTable.getIcon(i, 0).matches("blue.gif"))
    {                                   
      if (myTable.getRowValue(i, 1).contains("ble."))
      {
        counter1++;
      }    
      if (myTable.getRowValue(i, 1).contains("cle."))
      {    
        counter2++;
      }
      if (myTable.getRowValue(i, 1).contains("tion."))
      {
        counter3++;
      }
    }
  }
  System.out.println(counter1);
  System.out.println(counter2);
  开发者_如何学CSystem.out.println(counter3);
}


Move the initialization of the counter variables inside the for loop.

You need to reset the values to zero each time through the loop. The counters just keep counting because you only set them to zero at the beginning of the process, but not before x=2 and x=3.

Change this:

int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
for (int x = 1; x < 4; x++) {
    myTable.goToValue(x);

To this:

for (int x = 1; x < 4; x++) {
    int counter1 = 0;
    int counter2 = 0;
    int counter3 = 0;
    myTable.goToValue(x);


Try initialising counter1, counter2 and counter3 outside the first for loop.


I don't quite understand what you are trying to do here, but if your are counting the number of lines, shouldn't you put

 int counter1 = 0;
 int counter2 = 0;
 int counter3 = 0; 

outside the for loop?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜