Is my char checking logic wrong?

Asked

Viewed 52 times

0

I am reading a row of a file and I need the loop to stop when I find a space or a =. I did the code below but it is not working, even if it has space or = on the line, it continues the loop.

for (int i = 0; i < line.length(); i++){
    if (line.charAt(i) != ' ' || line.charAt(i) != '='){
    instruction += line.charAt(i);
    continue;
} 

I can’t find my mistake.

4 answers

1

Use break instead of continue

 for (int i = 0; i < line.length(); i++) {
  if (line.charAt(i) == ' ' || line.charAt(i) == '=') {
   break;
 }
  instruction += line.charAt(i);
}

1

  1. To STOP the loop, use the command break. The continue actually skips to the next loop item.

  2. There is a logic error in the code below:

    if (line.charAt(i) != ' ' || line.charAt(i) != '=')
    

Note that the if is checking whether the char is different from ' ' OR OTHER THAN '='. As there is no possibility of the char be equal to both, the condition will ALWAYS be true.

0

Gustavo, you can use break; and adjust some details of your code, such as closing the "}" for loop as well. Following example:

for (int i = 0; i < line.length(); i++){
    if (line.charAt(i) != ' ' && line.charAt(i) != '='){
       instruction += line.charAt(i);
   } else {
      break;
   }
}

0

This logic solves, so the String Instruction will not have blank space and the equality symbol.

    for (int i = 0; i < line.length(); i++){
        if (line.charAt(i) == ' ' || line.charAt(i) == '='){
            continue;
        }
        instruction += line.charAt(i);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.