【发布时间】:2011-09-05 03:52:50
【问题描述】:
简而言之,这就是我想要做的:
我想读取文件并检测符号后面的字符是数字还是单词。如果是数字,我想把前面的符号删掉,把数字翻译成二进制,替换到文件中。如果是单词,我想首先将字符设置为数字 16,但是,如果使用另一个单词,我想将 1 添加到原始数字并继续循环直到它到达输入的末尾。
当我对想要输入和读取的字符串进行硬编码时:
String input = "@5\n@word1\n@word2\n@word1\n@6";
String[] lines = input.split("\n"); // divide up the array
或者:
@5
@word1
@word2
@word1
@6
然后它输出我想要它输出的内容:
101
10000
10001
10000
110
但是当我输入 anyLines[i] (一个包含文件信息的数组,如果选择另一个文件,则可以更改):
String input = anyLines[i];
String[] lines = input.split("\n");
同样的数据,突然输出不正确:
101
10000
10000 <-- PROBLEM - should be 10001
10000
110
现在的问题是 wordValue 不会增加。在硬编码字符串中,wordValue 正确递增。
这是我的总体方法:
try {
ReadFile files = new ReadFile(file.getPath());
String[] anyLines = files.OpenFile();
int i;
// test if the program actually read the file
for (i=0; i<anyLines.length; i++) {
String input = anyLines[i];
String[] lines = input.split("\n");
int wordValue = 16; // to keep track words that are already used
Map<String, Integer> wordValueMap = new HashMap<String, Integer>();
for (String line : lines) {
// if line doesn't begin with "@", then ignore it
if ( ! line.startsWith("@")) {
continue;
}
// remove &
line = line.substring(1);
Integer binaryValue = null;
if (line.matches("\\d+")) {
binaryValue = Integer.parseInt(line);
}
else if (line.matches("\\w+")) {
binaryValue = wordValueMap.get(line);
// if the map doesn't contain the word value,
// then assign and store it
if (binaryValue == null) {
binaryValue = wordValue;
wordValueMap.put(line, binaryValue);
wordValue++;
}
}
// I'm using Commons Lang's
// StringUtils.leftPad(..) to create the zero padded string
System.out.println(Integer.toBinaryString(binaryValue));
}
}
}
请您指出正确的方向吗?
【问题讨论】:
-
可能是输入错误/不同。将
anyLines作为一个数组,这有点令人困惑,但随后您拆分每个数组元素,就好像每个元素本身就是一个文件一样。 -
@pickypig,没关系,我修好了。但现在,它循环了 16 次。
标签: java string file increment