0

I'm trying to make a comparison between two arrays called opCode[] and commands[]. My objective is to check for string equality, then display the corresponding string stored in another array called bin[]. I'm trying to simulate an assembler.

public class Assembler 
{
  static String[] commands = new String[23];
  static String[] bin = new String[23];
  
  static String[] opCode;
  static String[] operand;
  
  public static void main(String[] args) 
  {
    try {
      /*
       * Parse mac1 text file
       */
      BufferedReader br = new BufferedReader(new FileReader("mac1.txt"));

      int i = 0;
      String line;
      String[] data = null;
      
      while((line = br.readLine()) != null) {
        data = line.split("\\|");
        commands[i] = data[0];
        bin[i] = data[1];
        i++;      
      }
      
      /*
       * Parse algo text file
       */
      FileReader file = new FileReader("algo.txt");
      BufferedReader br2 = new BufferedReader(file);
      
      Path f = Paths.get("algo.txt");
      long count = Files.lines(f).count();

      opCode = new String[(int) count];
      operand = new String[(int) count];
      
      
      i = 0;
      String line2;
      String[] data2 = null;
      
      while((line2 = br2.readLine()) != null) {
        data2 = line2.split(" ");
        opCode[i] = data2[0];
        operand[i] = data2[1];
        i++;      
      }
      
    }
    catch(IOException e) {
      System.out.println("File not found!"); //displays error msg if file is not found
    }
    translate();
  }
  
  public static void translate()
  {
    for(int i = 0; i < opCode.length; i++)
    {
      if(commands[i] == opCode[i])
      {
        System.out.println(bin[i]);
      }
    }
  }
}

commands[] / bin[]

enter image description here

opCode[] / operand[]

enter image description here

translate() isn't outputting anything. It could be the way I set up the the loop and conditional. What I'm trying to do is traverse through opCode[] and check for the matching strings in commands[], then output the corresponding binary sequence in bin[]. Thanks in advance!

Nico
  • 73
  • 8

2 Answers2

1

Since strings are objects, you should avoid comparison using ==

 //commands[i] == opCode[i]
 commands[i].equals(opCode[i])

Comparison using == is effective only for String Pool. Equals will always output reliable result with strings.

Siberio
  • 105
  • 9
  • Thanks so much! I saw @SzaPe's suggestion first before this, but thank you for the useful tip anyway! – Nico Mar 01 '21 at 09:35
1

You're missing an extra loop in the translate method, to check the whole commands array. Also use equals for strings instead of ==.

    public static void translate() {
      for (int i = 0; i < opCode.length; i++) {
        for (int j = 0; j < commands.length; j++) {
          if (commands[j].equals(opCode[i])) {
            System.out.println(bin[j]);
          }
        }
      }
    }
SzaPe
  • 131
  • 1
  • 8