所以我有这个方法应该读取文件并检测符号后面的字符是数字还是单词。如果是数字,我想删除它前面的符号,将数字转换为二进制文件并将其替换为文件。如果是单词,我想首先将字符设置为数字16,但是如果使用另一个单词,我想将1添加到原始数字。
这是我正在使用的输入:
这是我的方法:
try {
ReadFile files = new ReadFile(file.getPath());
String[] anyLines = files.OpenFile();
int i;
int wordValue = 16;
// to keep track words that are already used
Map<String, Integer> wordValueMap = new HashMap<String, Integer>();
for (String line : anyLines) {
if (!line.startsWith("@")) {
continue;
}
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 want to replace with this
System.out.println(Integer.toBinaryString(binaryValue));
}
for (i=0; i<anyLines.length; i++) {
// --> Here are a bunch of instructions that replace certain strings - they are the lines after @ symbols <--
// --> I'm not going to list them ... <--
System.out.println(anyLines[i]);
所以问题是,如何按顺序替换那些以(“@”逐行)开头的行?
我基本上希望输出看起来像这样:
101
1110110000010000
10000
1110001100001000
10001
1110101010001000
10001
1111000010001000
10000
1110001110001000
10010
1110001100000110
10011
1110101010000111
10010
1110101010000111
答案 0 :(得分:1)
我不太了解逻辑。如果您只是尝试按顺序替换所有@符号,为什么不按顺序将所有数字读入List
,直到看到@符号为止。然后,您可以从List
开始按顺序替换它们(或者Queue
,因为您首先需要先输出)。这是否满足您的要求?
如果您必须保留wordValueMap
,则在填充wordValueMap
并将其写入控制台后,下面的代码应循环显示。它使用与您首先填充地图相同的逻辑,并输出应替换的值。
boolean foundAt = false;
for (i=0; i<anyLines.length; i++) {
// --> Here are a bunch of instructions that replace certain strings - they are the lines after @ symbols <--
// --> I'm not going to list them ... <--
if (anyLines[i].startsWith("@")) {
foundAt = true;
String theLine = anyLines[i].substring(1);
Integer theInt = null;
if (theLine.matches("\\d+")) {
theInt = Integer.parseInt(theLine);
}
else {
theInt = wordValueMap.get(anyLines[i].substring(1));
}
if(theInt!=null) {
System.out.println(Integer.toBinaryString(theInt));
}
else {
//ERROR
}
}
else if(foundAt) {
System.out.println(anyLines[i]);
}
}
当我运行此循环时,我会从您的问题中获得您正在寻找的输出:
101
1110110000010000
10000
1110001100001000
10001
1110101010001000
10001
1111000010001000
10000
1110001110001000
10010
1110001100000110
10011
1110101010000111
10010
1110101010000111
我希望这会有所帮助,但请看一下我上面的问题,看看你能否以更直接的方式做到这一点。