Results 1 to 5 of 5
Thread: For loop
- 01-17-2012, 08:06 PM #1
Member
- Join Date
- May 2011
- Posts
- 84
- Rep Power
- 0
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?
Java 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; } }
- 01-17-2012, 08:13 PM #2
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.
- 01-17-2012, 08:20 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,413
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 01-17-2012, 08:40 PM #4
Member
- Join Date
- May 2011
- Posts
- 84
- Rep Power
- 0
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():
Java 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); }
- 01-17-2012, 09:34 PM #5
Member
- Join Date
- May 2011
- Posts
- 84
- Rep Power
- 0
Similar Threads
-
Converting a for loop to a do-while loop
By awesom in forum New To JavaReplies: 1Last Post: 11-23-2011, 03:02 PM -
Problem with while loop, assigning a variable with a different value every loop? Help
By JavaProg in forum New To JavaReplies: 2Last Post: 11-07-2011, 02:25 AM -
Is it Possible? Array elements Initialized in Loop, can it be viewed outside loop?
By JPH in forum New To JavaReplies: 1Last Post: 10-01-2011, 02:12 AM -
JTextField loop 2x for-loop WEIRD!
By Streetproject in forum AWT / SwingReplies: 2Last Post: 02-16-2011, 05:46 PM -
Convert do while loop to for loop
By sandeeptheviper in forum New To JavaReplies: 3Last Post: 01-03-2011, 12:37 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks