COM Port Error: Port Not Found

Even with this code, the error still appears.

  if ((Serial.list().length > num_ports) && !device_detected)
  {
    device_detected = true;
    boolean str_match = false;
    if (num_ports == 0) {detected_port = Serial.list()[0];}
    else
    {
      for (int i = 0; i < Serial.list().length; i++)
      {
        for (int j = 0; j < num_ports; j++)
        {
          if (Serial.list()[i].equals(port_list[j])) {break;}
          if (j == (num_ports - 1))
          {
            str_match = true;
            detected_port = Serial.list()[i];
          }
        }
      }
    }
    mySerial = new Serial(this, detected_port, 9600);
  }
  else if ((Serial.list().length == 0)){device_detected = false;}