Answer the question
In order to leave comments, you need to log in
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
//Проверяем, не ЗАБЫЛ ли пользователь ввести свое имя?
if (name == null || name.trim().isEmpty()) { ...
name == "" - Not correct.
read the docs.
generally something like that.
if (!"".equals(name))
{
...
}
To everything above, add curly braces after the else and at the end.
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 questionAsk a Question
731 491 924 answers to any question