【问题标题】:Comparing strings stored in two different arrays and output a string from another array if the strings match [duplicate]比较存储在两个不同数组中的字符串,如果字符串匹配,则从另一个数组输出一个字符串[重复]
【发布时间】:2021-03-01 09:20:44
【问题描述】:

我正在尝试在两个名为 opCode[] 和 commands[] 的数组之间进行比较。我的目标是检查字符串是否相等,然后显示存储在另一个名为 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[]

操作码[] / 操作数[]

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

【问题讨论】:

    标签: java arrays string equals


    【解决方案1】:

    您在 translate 方法中缺少一个额外的循环,用于检查整个命令数组。字符串也可以使用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]);
              }
            }
          }
        }
    

    【讨论】:

      【解决方案2】:

      由于字符串是对象,你应该避免使用==进行比较

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

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

      【讨论】:

      • 非常感谢!在此之前我首先看到了@SzaPe 的建议,但无论如何感谢您提供有用的提示!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多