Reputation: 137
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
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
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
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
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