1

I'm writing small condition to check if certain character are exist or not in java. This is my string: May i know how much I spent on food?

I'm checking if food string is exist or not, if i check "food" in if condition I'm getting proper response, if i use "Food" or "fOod" or "fOOd" or "fooD" its always going to else block. What I'm doing wrong here:

String food = "may i know how much I spent on food";

if(food.contains("Food")) {
    System.out.println("Food Expense is 32");

} else {
    System.out.println("Not Matching");
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
mark
  • 219
  • 1
  • 8
  • 19

2 Answers2

3

That is because the difference in cases. "Food".equals("food") will give you false. To solve the problem of cases you can convert everything to lower when searching

if (food.toLowerCase().contains("Food".toLowerCase())) {}

And you can have any variation of food in the if condition. No need to worry about case sensitivity with this

anon
  • 1,258
  • 10
  • 17
0

Try this

if(food.toLowerCase().contains("Food".toLowerCase())) {
System.out.println("Food Expense is 32");

} else {
System.out.println("Not Matching");
}
Mike Smith
  • 23
  • 1
  • 6
  • Advice: "Try this" answers generally don't get upvotes. An answer should explain what was wrong with the original code, and how the new code fixes it. (Contrast the other answer to this question.) – Kevin J. Chase Jul 24 '17 at 02:53