简而言之,这就是我想做的事情:
我想读取一个文件并检测符号后面的字符是数字还是单词。如果是数字,我想删除它前面的符号,将数字翻译成二进制并替换到文件中。如果是一个单词,我想首先将字符设置为数字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));
}
}
}
您能给我指出正确的方向吗?
最佳答案
乍一看,代码看起来还不错。你最好的选择是在处理这些行时打印出来,看看它们是否是……奇怪的……格式:
for (String line : lines)
System.out.println ("[" + line + "]");
事实上,我会全力以赴,在每行更改某些内容之后放置一个打印语句(打印序列号和更改的内容),以确保不会出现意外的影响:
类似于:
else if (line.matches("\\w+")) {
binaryValue = wordValueMap.get(line);
System.out.println ("A: binval set to " + binaryValue);
// if the map doesn't contain the word value,
// then assign and store it
if (binaryValue == null) {
binaryValue = wordValue;
System.out.println ("B: binval set to " + binaryValue);
wordValueMap.put(line, binaryValue);
System.out.println ("C: put " + binaryValue +
", now " + wordValueMap.get(line));
wordValue++;
System.out.println ("C: wordval set to " + wordValue);
}
}
这种 printf
调试方法通常非常有用,尽管您也可以选择使用调试工具:-)
关于java - 硬编码字符串有效,输入字符串无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6182424/