我正在编写一个基本的汇编程序,它将 asm 文件转换为二进制指令。其中一个步骤是测试文件的每一行是否以@
开头。我需要循环文件中每行的第一个字母,并测试哪些以@
开头。
到目前为止,我的代码不会连续循环,而是仅测试第一行的第一个字符,就是这样。这是:
try (Scanner s = new Scanner(chooser.getSelectedFile().getName())) {
while (s.hasNextLine()) {
//int change2Int = s.nextInt();
String linept = "";
linept += (stringBuffer.charAt(0));
s.nextLine(); // ignore the rest of the line
// i++;
System.out.println(linept);
}
}
以下是我的整个代码,以便更清晰:
public class Assembler
{
public static void main(String[] args) throws IOException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".asm")
|| f.isDirectory();
}
public String getDescription() {
return "asm File";
}
});
int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getName();
System.out.println(name);
}
BufferedReader bufferedReader = new BufferedReader(new
FileReader(chooser.getSelectedFile().getName()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while((line =bufferedReader.readLine())!=null){
stringBuffer.append(line).append("\n");
Assembler assembler = new Assembler();
// assembler.AorC(stringBuffer);
}
System.out.println(stringBuffer);
try (Scanner s = new Scanner(chooser.getSelectedFile().getName())) {
while (s.hasNextLine()) {
//int change2Int = s.nextInt();
String linept = "";
linept += (stringBuffer.charAt(0));
s.nextLine(); // ignore the rest of the line
// i++;
System.out.println(linept);
}
}
}
}
答案 0 :(得分:1)
我认为最好更改输入文件的处理方法,并使用FileReader代替Scanner:
try {
FileReader fileReader = new FileReader(arq.getSelectedFile());
BufferedReader bufferedReader = new BufferedReader(fileReader);
int sum;
String linept = "";
while ( ( linept = bufferedReader.readLine() ) != null) {
if(linept.startsWith("@") ){
System.out.println(sum);
}
}
System.out.println("Result: "+sum);
}