java - 在Java中访问数组外循环的问题
问题描述
编辑:我采取了不同的方法,现在可以了!感谢帮助过的人!
我正在尝试编写一个模拟汇编程序的程序。我能够阅读指令集(见下文)以及将要组装的代码中的示例行。我还能够将每个文件的组件分成不同的数组。但是,每当我尝试打印出填充它们的循环之外的数组或只是一般地访问它们时,我突然无法获得正确的结果。
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() 时打印出数组中的最后一个元素。目标是采用这种特定语言编写的程序,并通过翻译组成二进制输出。
谢谢!
解决方案
您不应该为循环内的数组创建新实例……</p>
使用您当前的设置,每一行都会覆盖前一行;您看不到这一点,因为您从读取循环内部转储了输入。
接下来,您应该考虑为每一行的内容定义一个结构(Java 中的一个类),并将其存储到一个实例中List
,然后在读取所有行后将其转换为数组。或者,您可以在模拟系统内存的循环之外定义一个数组;显然,该数组需要足够大以容纳大多数输入文件。
推荐阅读
- c# - 获取 ArraySegment
来自 System.ServiceModel.Channels 消息 - javascript - 如果选择了特定的下拉选项,显示/隐藏表单行的最佳方式是什么?
- c++ - 如何查找 2d std::array 中的列数
- c++ - Opencv4 使用 pkg-config 给出未定义的参考错误
- java - 仅为一组实体配置 Hibernate 实体侦听器
- excel - Excel Services REST API 的 URI
- reactjs - React Js Data Table "No data available in table"
- ruby-on-rails - what to check if an attribute must be present in request payload of Json
- python - 文本文件中值的 Python 拆分函数
- javascript - React Js - get json array Image to JSX page of react dynamically