This site requires JavaScript, please enable it in your browser!
Greenfoot back
ItsJosh18
ItsJosh18 wrote ...

2016/1/27

Responding to text inputs

ItsJosh18 ItsJosh18

2016/1/27

#
Hi I have a question about responding to text inputs. What I want to have done is depending on the text inputted it will update a certain variable. Thanks -Joshua
davmac davmac

2016/1/27

#
In Java you can use "if" statements to change behaviour depending on the value of variables or expressions. This is fairly fundamental, so if you're not aware of how to use them I suggest that you go through the Joy of Code videos from the documentation page. (Or, if you know how to use "if" statements already, be clearer on the problem that you currently have).
ItsJosh18 ItsJosh18

2016/1/27

#
I have been having a problem with if statements. How do I get a variable to equal a string of text that is entered? This is the code i am having trouble with.
1
2
3
4
if(enTxt = "Have a nice day")
{
 xp = xp +10
}
It gives me an error saying I cannot convert text to a boolean. Thanks for your help -Joshua
danpost danpost

2016/1/27

#
In line 1, you are assigning "Have a nice day" to the variable 'enTxt' -- not asking if one equals the other. The conditional equality symbol is a double equal sign '=='. This can be used to determine if two values or objects are one in the same. Please note, however, that two different String objects, even if containing similar content, are still different strings. Actually, for two objects to be the same object,, both objects being compared must be located at the same memory address on your system. So, even if you had compared the two with:
1
if (enTxt == "Have a nice day")
the result will never be true. The reference to 'enTxt' will never be the same as the newly created reference to the literal string. To compare the contents of two different strings for equality, you will need to use the 'equals' method of the String class (inherited from the Object class -- overridden in the String class). This comparison will look like this:
1
if ("Have a nice day".equals(enTxt))
ItsJosh18 ItsJosh18

2016/1/27

#
Oh Ok thank you! :) -Joshua
You need to login to post a reply.