EDIT: I took a different approach, and it now works! Thanks to those who helped!
I'm trying to write a program that simulates an assembler. I was able to read in the instruction set (see below) as well as a sample line from the code that will be assembled. I was also able to separate the components of each file into different arrays. However, whenever I try to print out the arrays outside of the loops that populated them or just accessing them in general, I'm suddenly not able to get the right results.
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));
}
}
Input:
Output:
I guess my main question is how would I be able to access the arrays outside the loops as well as in other methods later down the line? It only prints out the last element in the array when using toString() outside the loops. The objective is to take a program written in this specific language and compose a binary output by means of translating.
Thanks!

