Mazzy
Mazzy

Reputation: 14227

set a boolean value

Hi I'm working with boolean values and I'm a little bit confused. I have a boolean value:

boolean answer;

This can have two values : yes or not.

If I insert from standard input the string "yes" it became true otherwise false. How can i do?

Upvotes: 2

Views: 60136

Answers (7)

OldCurmudgeon
OldCurmudgeon

Reputation: 65879

Something like this may be of value:

private static final Set yesSet = new HashSet( Arrays.asList( new String[] {"1", "aam", "ae", "ām", "ano", "âre", "avunu", "awo", "aye", "ayo", "baht", "bai",
  "bale", "bele", "beli", "ben", "cha", "chaï", "da", "dai", "doy", "e", "é", "éé", "eh", "èh", "ehe", "eja", "eny", "ere", "euh", "evet", "éwa", "giai",
  "ha", "haan", "hai", "hoon", "iè", "igen", "iva", "já", "jā", "ja", "jah", "jes", "jo", "ken", "kha", "khrap", "kyllä", "leo", "naam", "ndiyo", "o", "òc",
  "on", "oo", "opo", "oui", "ova", "ovu", "oyi", "po", "sci", "se", "shi", "si", "sim", "taip", "tak", "tiao", "true", "v", "waaw", "wè", "wi", "ya", "yan",
  "ydw", "yea", "yebo", "yego", "yes", "yo", "yoh", "za", "За", "Так", "Тийм", "نعم", "ใช่", "ค่ะ", "ครับ",
} ) );
public static final boolean stringToBool ( String s ) {
  return ( yesSet.contains( s.toLowerCase() ) );
}

Derived from FreeLang

Upvotes: 3

Eng.Fouad
Eng.Fouad

Reputation: 117675

boolean answer = new Scanner(System.in).nextLine().equalsIgnoreCase("yes");

Upvotes: 0

Travis J
Travis J

Reputation: 82337

If your string is saved into response (string response):

if(response.equals("yes")){
 answer = true;
}else{
 answer = false;
}

Upvotes: 0

litterbugkid
litterbugkid

Reputation: 3666

boolean answer;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
try{
   input = br.readLine();
}
catch(IOException e){}

if (input.compareTo("yes") == 0)
{ 
   answer= True;
}
else{
   answer = False;
}

Upvotes: 0

Jeff Olson
Jeff Olson

Reputation: 6473

This should do it:

boolean answer;
String input = "yes"
if (input.equals("yes")) {
   answer = true;
}

Upvotes: 0

Colby
Colby

Reputation: 459

assuming input is your string:

boolean answer = input.equalsIgnoreCase("yes");

Upvotes: 11

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272762

You need to perform a string comparison. Use String.equals:

String a = "foo";
String b = "bar";
boolean c = a.equals(b);

Upvotes: 1

Related Questions