Hailei Edwards
Hailei Edwards

Reputation: 137

Android Java Strings

For Strings..

How can i Detect if the string "name" has the text "Hello" a toast will come up saying yes but if it doesn't a toast will come up saying no? my code:

        String ft;
    if(ft.contains("Hello")){

        Toast.makeText(main.this ,"Yes", Toast.LENGTH_SHORT).show();
        }
        else{
        Toast.makeText(main.this ,"No", Toast.LENGTH_SHORT).show();
        }

I get a error at ft on if(ft.contains("Hello")) {

"The local variable ft may not have been initialized"

Upvotes: 1

Views: 2330

Answers (4)

Kartik Domadiya
Kartik Domadiya

Reputation: 29968

You declared String, but you didn't initialize. Initializing it is setting them equal to a value:

String ft;        // This is a declaration

String ft="";    // This is an initialization

Perhaps String ft = ""; is "declaration and initialization.

You get the error because you haven't initialized the variable, but you use them (e.g., ft.compare()) in if condition.

So try replacing String ft; with String ft="";

Upvotes: 1

ngesh
ngesh

Reputation: 13501

if(name.contains("Hello")){

Toast.makeText(activity.this ,"Yes", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(activity.this ,"No", Toast.LENGTH_SHORT).show();
}

Updated:

String ft = "";

    String ft= name.equals("Hello") ? "Yes" : "No";
     Toast.makeText(activity.this ,ft, Toast.LENGTH_SHORT).show();

Upvotes: 1

anujprashar
anujprashar

Reputation: 6335

if(name.equals("Hello")){
    Toast.makeText(this, "Yes", Toast.LENGTH_LONG).show();
}else{
     Toast.makeText(this, "no", Toast.LENGTH_LONG).show();
}

Upvotes: 0

Peter Knego
Peter Knego

Reputation: 80350

String text;
if(name.equals("Hello")){
    text = "Yes";
} else {
    text = "No";
}

Toast toast = Toast.makeText(context, text, duration);
toast.show();

You can also use shorthand expression instead of if:

String text = name.equals("Hello") ? "Yes" : "No";

Upvotes: 2

Related Questions