忽略文件中的最后一个指定字符

时间:2011-07-27 13:56:11

标签: java

我有这部分代码:

int numberStars =0;
int counter =0;

while (file.hasNext()) {
  String contents = file.next();
  {             
    if (contents.contains("*")) {
      numberStars = counter;                    
      continue;
    }
    counter++;              
  }
}

所以,如果我有一个包含

之类的文本文件

ha de fa * la we * ba *

输出为3,5,6。如何更改此循环以便不计算最后一个*(因此6将不存在),以及我如何确保每次将值分配给numberStars时,该值将在另一个部分中使用方法?

非常感谢。

3 个答案:

答案 0 :(得分:0)

如果我理解你想要的东西,那么保存最后一个计数器,最后只使用它。

int lastcounter = -1;
boolean starfound = false;
while (file.hasNext()) {
  String contents = file.next();
  {             
    if (contents.contains("*")) {
      lastcounter = numberstars;
      numberStars = counter;
      starfound = true;                    
    } else {
      counter++;              
    }
    if(starfound) {
       // do something
       starfound = false;
    }
  }
}
return lastcounter;

答案 1 :(得分:0)

您可能希望存储counter的值列表,而不是仅存储一个int。像

这样的东西
List<Integer> numberStars = new ArrayList<Integer>();
int counter = 0;
while (file.hasNext()) {
    String contents = file.next();
    if (contents.contains("*")) {
        numbStars.add(counter);
        continue;
    }
    counter++;
}
numberStars.remove(numberStars.size() - 1); // remove last value
// all the values are now available in the numberStars list

答案 2 :(得分:0)

只包含一行文件? 我建议用BufferedReader读取文件然后 使用String.split()方法查找星号数。

BufferedReader br = new BufferedReader(new FileReader("yourFile"));
String line;
String[] tmp;
int counter;

while( (line=br.readLine() ) !=null)
{
    tmp = line.split(" ");

    //Ignoring the last element
    for(int i = 0; i < (tmp.length-1); i++)
    {
          if(tmp[i].contains("*"))
              counter++;
    }


}
相关问题