我一直在尝试使用下面的代码查找标签和单个空格字符的总数。所以,如果我使用这个
if (c[i] == '\t') {
++tabcount;
}
它给tabCount = 0,如果我想使用这个
获得单个空格字符的数量if (c[i] == ' ') {
++singlescpacecount;
}
它给出了整个文件中的空格总数。
tabCount的代码是
public static void TabCount(String filename) throws IOException{
int tabcount = 0;
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\t') {
++tabcount;
}
}
}
System.out.println("The total number of tabcounts are :" + tabcount);
} finally {
is.close();
}
}
提前致谢。
答案 0 :(得分:0)
至少部分问题必须是OP的输入文件不包含预期的标签。如@Andreas所述,基本代码结构 计算选项卡。但是,我曾建议确保文件不会多次迭代以计算各种字符。这是一个如何做到这一点的实现。它不是最佳的,而是具有启发性的。
/**
* A class to accumulate results
*/
static class Results
{
private int tabs = 0;
private int spaces = 0;
public void incTabCount()
{
++tabs;
}
public void incSpaceCount()
{
++spaces;
}
public int getTabCount()
{
return tabs;
}
public int getSpaceCount()
{
return spaces;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("tabs: ");
sb.append(tabs);
sb.append("\nspaces: ");
sb.append(spaces);
return sb.toString();
}
}
/**
* Iterate the file once, checking for all desired characters,
* and store in the Results object
*/
public static Results countInFile(String filename) throws IOException
{
// create results
Results res = new Results();
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
// see if we have a tab
if (c[i] == '\t') {
res.incTabCount();
}
// see if we have a space
if (c[i] == ' ') {
res.incSpaceCount();
}
}
}
} finally {
is.close();
}
return res;
}
public static void main(String[] args)
{
Results res;
try {
res = countInFile("f:/tmp/test.txt");
System.out.println(res);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输入文件(标签位于第一行“has”后面):
这一行有\ ta标签 还有7个空格?
根据输入文件,结果如预期:
标签:1
空格:7
编辑:作为旁白,有一个最终会更可测试的修改。如果要将文件处理与输入流中的计数分开,则可以更轻松地将已知输入提供给系统。例如,稍微修改上述内容:
/**
* Counts in a stream the number of tabs and spaces, and returns
* the Results
*/
private static Results countInStream(InputStream is) throws IOException
{
// create results
Results res = new Results();
try {
byte[] c = new byte[1024];
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
// see if we have a tab
if (c[i] == '\t') {
res.incTabCount();
}
// see if we have a space
if (c[i] == ' ') {
res.incSpaceCount();
}
}
}
}
finally {
}
return res;
}
此方法可能会传递String
:
String s = "This\thas\ttabs.\nAs well as spaces";
InputStream is = new ByteArrayInputStream(s.getBytes("UTF8"));
res = countInStream(is);
System.out.println(res);
由于现在测试主逻辑变得容易得多,因此可以清楚地看到基数计数按预期运行。可以修改上面建议的countInFile
方法以从文件中打开InputStream,然后调用countInStream()
。这种方法可以减少关于方法的逻辑是否存在争议,或内容发送到方法的争论。