以下是代码:
读取文件方法:
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.List;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadFile {
private String path;
// create a method which takes in the classpath of the file
public ReadFile(String filePath) {
path = filePath;
}
public String[] OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
List<String> textData = new LinkedList<String>();
String line;
while ((line = textReader.readLine()) != null) {
Pattern pattern = Pattern.compile("//.*$", Pattern.DOTALL);
Matcher matcher = pattern.matcher(line);
line = matcher.replaceFirst("");
if (line.trim().length()==0) continue;
if (!line.startsWith("//")) { textData.add(line); }
else if (!line.startsWith("(")) { textData.add(line); }
}
// close the line-by-line reader and return the data
textReader.close();
return textData.toArray(new String[textData.size()]);
}
}
和我的主要方法:
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++) {
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 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));
}
答案 0 :(得分:2)
您有两个嵌套循环,每个循环执行anyLines.length
次。如果文件中有四行,则内循环将执行16次。