-
For loop
Hi,
I have an array "commands" containing two values. I want to compare "inputLine" to every value in the array and if there is a match - return "Command found: " + command message. But whatever value I pass into the method, the outputLine always stays null.
Why is this happening?
Code:
public class Processing {
String[] commands = {"help", "start"};
public String sortCommand(String inputLine) {
String outputLine = null;
for (int i = 0; i < commands.length; i++) {
if (inputLine == commands[i]) {
outputLine = "Command found: " + commands[i];
break;
}
}
return outputLine;
}
}
-
Re: For loop
Have you tried verifying that whatever you're passing to the sortCommand function is what you think it is? I tried sortCommand("help") and it worked as you were expecting. Maybe check how you are getting your input.
-
Re: For loop
Don't compare Strings for equality with the == operator; use the equals(...) method instead; also read the API documentation for the String class.
kind regards,
Jos
-
Re: For loop
@JosAH
Thanks, I corrected it to equals.
@Shoss
I think you are right. I tries to debug it myself but I still cannot find the source of this "null" value. Here is the code that sends "inputLine" to Processing.sortCommand():
Code:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Processing process = new Processing();
outputLine = process.sortCommand(null);
while ((inputLine = in.readLine()) != null) {
out.println("->" + "\033[36m" + inputLine + "\033[0m");
outputLine = process.sortCommand(inputLine);
out.println(outputLine);
}
-
Re: For loop
Problem solved, thanks for help.