-3

Hi i'm getting the error:

cannot find symbol - variable Andrew for this method.

What do I need to change?

/**
* Create a method that says hi if the name is the same as yours and go away otherwise.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class String
{
public void greeting(String name) {
    String myName;
    myName = Andrew;
    if (name == myName) {
        System.out.println("Hi");
    }
        else {
            System.out.println("Go away");
        }

    }

}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
user1605782
  • 111
  • 1
  • 2
  • 8
  • Please accept one of the answers as an answer to your question and upvote if it help you. It is the least you can do when somebody invests time in helping you out. You have asked six questions and received answers to them all, but never accepted one of them. – MarchingHome Oct 22 '12 at 08:02

5 Answers5

2

use equals() to compare String, == will compare reference, also there is no declaration of Andrew

jmj
  • 237,923
  • 42
  • 401
  • 438
1
myName = Andrew;

There you are using Andrew which is not declared yet, so you cannot use it.

To be able use it you have to first declare (also initialize correctly to see correct result at runtime)

String Andrew;

like that before you use it.

One other problem is your class name String. In the method public void greeting(String name), which String class do you mean, your own or java.lang.String.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • In that case, it is recommended to have andrew start with a non-capital letter. – MarchingHome Oct 17 '12 at 01:49
  • 1
    @MarchingHome: Yes, I was about to add that but there I was what to add and what not to. I think it's better for him to learn about the Java Naming Convention. – Bhesh Gurung Oct 17 '12 at 01:52
1
String myName = "Andrew";
if (name.equals(myName)) {
    System.out.println("Hi");
}

Better to do the comparison other way round e.g. myName.equals(name) in place of name.equals(myName) since myName is not null for sure while name can be null, which will result into NullPointerException.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

Try it like this:

public class String
{
public void greeting(String name) {
    String myName;
    myName = "Andrew";
    if (name.equals(myName)) {
        System.out.println("Hi");
    }
        else {
            System.out.println("Go away");
        }

    }

}
MarchingHome
  • 1,184
  • 9
  • 15
0
String myName;
myName = Andrew;

And what is Andrey? According to Java syntax, compiller expects it's a variable, but actually there is not such a variable. I suppose you want to write something like

String myName;
myName = "Andrew";//this is correct initialization