比较存储在两个不同数组中的字符串,如果字符串匹配则从另一个数组中输出一个字符串

Comparing strings stored in two different arrays and output a string from another array if the strings match

我正在尝试比较名为 opCode[] 和 commands[] 的两个数组。我的 objective 是检查字符串是否相等,然后显示存储在另一个名为 bin[] 的数组中的相应字符串。我正在尝试模拟一个汇编器。

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]);
      }
    }
  }
}

命令[] / bin[]

opCode[] / operand[]

translate() 未输出任何内容。这可能是我设置循环和条件的方式。我想做的是遍历 opCode[] 并检查 commands[] 中的匹配字符串,然后在 bin[] 中输出相应的二进制序列。提前致谢!

由于字符串是对象,您应该避免使用 ==

进行比较
 //commands[i] == opCode[i]
 commands[i].equals(opCode[i])

使用==比较只对String Pool有效。 Equals 将始终使用字符串输出可靠的结果。

您在翻译方法中缺少一个额外的循环,用于检查整个命令数组。对于字符串也使用 equals 而不是 ==.

    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]);
          }
        }
      }
    }