【发布时间】:2021-05-30 16:56:36
【问题描述】:
编辑:我采用了不同的方法,现在可以了!感谢那些帮助过的人!
我正在尝试编写一个模拟汇编程序的程序。我能够阅读指令集(见下文)以及将要组装的代码中的示例行。我还能够将每个文件的组件分成不同的数组。但是,每当我尝试打印出填充它们的循环之外的数组或只是一般地访问它们时,我突然无法获得正确的结果。
public class Assembler {
public static String[] data;
public static String[] commands;
public static String[] bin;
public static String[] data2;
public static String[] opCode;
public static String[] operand;
public static void main(String[] args) {
try {
File input = new File("mac1.txt");
Scanner in = new Scanner(input);
/*
* Parse mac1 text file
*/
while(in.hasNextLine()) {
String line = in.nextLine(); //reads the text file one line at a time
data = line.split("\\|"); //delimits the data by "|" and stores it in array data[]
//assigns size to the arrays that will hold the mnemonics and binary
commands = new String[data.length - 1];
bin = new String[data.length - 1];
//populates the arrays with corresponding data then displays them
for(int i = 0; i < bin.length; i++)
{
commands[i] = data[i];
bin[i] = data[i + 1];
System.out.println(commands[i] + " " + bin[i]);
}
}
File input2 = new File("algo.txt");
Scanner in2 = new Scanner(input2);
System.out.println("--------------------------------");
while(in2.hasNextLine()) {
String line2 = in2.nextLine(); //reads the text file one line at a time
data2 = line2.split(" "); //delimits the data by "|" and stores it in array data[]
//assigns size to the arrays that will hold the mnemonics and binary
opCode = new String[data2.length - 1];
operand = new String[data2.length - 1];
//populates the arrays with corresponding data then displays them
for(int i = 0; i < opCode.length; i++)
{
opCode[i] = data2[i];
operand[i] = data2[i + 1];
System.out.println(opCode[i] + " " + operand[i]);
}
}
/*
* Outputs only the last element = 11111110
*/
for(int i = 0; i < bin.length; i++)
{
System.out.println(bin[i]);
}
translate(bin, commands);
in.close();
}
catch(IOException e) {
System.out.println("File not found!"); //displays error msg if file is not found
}
}
/*
* Outputs only the last element = 11111110
*/
public static void translate(String[] bin, String[] commands)
{
System.out.println(Arrays.toString(bin));
}
}
输入:
输出:
我想我的主要问题是我如何能够访问循环之外的数组以及以后的其他方法?它仅在循环外使用 toString() 时打印出数组中的最后一个元素。目标是获取用这种特定语言编写的程序,并通过翻译组成二进制输出。
谢谢!
【问题讨论】:
-
@Henry 我计划在 in.close() 之前以及我尚未创建的其他方法中访问它们。