K
K
Kirill Romanenko2014-07-02 01:04:21
Java
Kirill Romanenko, 2014-07-02 01:04:21

Can you tell me where is the error in Java code?

Here is my piece of code. At first, everything is correct, the program seems to start and run properly, but here you can see a new piece - I decided now to also check, what if the player will not enter his name at all? Before this, the program just ran without a name - with an empty space instead.
However, the program simply ignores my check and works as it should without the new "if-then"! It's like she doesn't understand that I'm asking to check if there is an empty space in place of the player's name. Maybe I forgot some signs? Or is it necessary to write not if (name=="") but something else?
//Request the username for further use in dialogs.
System.out.println("Hi. What's your name?");
Stringname=in.readLine();
//Check if the user has entered their name?
if (name=="")
{
System.out.println("Don't want to talk? Suspicious..");
System.out.print("The saleswoman is frowning. Looks like she trusts you a little less now.");
}
//if entered, then next:
else
System.out.println("What do you want to buy, " + name + "?");
System.out.println("1) Cigarettes;");
System.out.println("2) Bread;");
System.out.println("3) Milk;");
System.out.println("(Enter a number)");
//Receive the player's response. Remember as "y":
String sn=in.readLine();
int y=Integer.parseInt(sn);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
pi314, 2014-07-02
@kiralis39

//Проверяем, не ЗАБЫЛ ли пользователь ввести свое имя?
if (name == null || name.trim().isEmpty()) { ...

such a "cunning" check is needed, because readLine() may well return null, and then we'll fall NPE on name.trim()
In Java, string comparison is done like this:
a name=="" will compare the name object with another, new String object, with the value "" ... which, of course, will never be equal (regardless of whether the VALUES of the strings are equal to each other), because these are two different objects!

M
Marat S, 2014-07-02
@aratj

name == "" - Not correct.
read the docs.
generally something like that.
if (!"".equals(name))
{
...
}

M
Maxim Moseychuk, 2014-07-02
@fshp

To everything above, add curly braces after the else and at the end.

S
sgtraf, 2014-09-26
@sgtraf

habrahabr.ru/post/49582
In Java, there are two ways to compare objects for equality, == and the equals method.
== is used for primitive types. For its use with objects, smart people either beat on the ears or thank you in every possible way - for objects == this is only a comparison by reference ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question