问题描述
|
因此,我有此方法应读取文件并检测符号后的字符是数字还是单词。如果是数字,我想删除它前面的符号,将数字转换为二进制并将其替换在文件中。如果是一个单词,我想首先将字符设置为数字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
解决方法
我不太了解逻辑。如果只是尝试按顺序替换所有@符号,为什么不按顺序将所有数字读入
List
,直到看到@符号。然后,您可以从List
(或Queue
,因为您要先进先出)开始按顺序更换它们。满足您的要求吗?
如果必须保留ѭ5,则下面的代码应在填充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
我希望这会有所帮助,但请看一下我上面的问题,看看是否可以更直接地做到这一点。