2

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?

Mazzy
  • 13,354
  • 43
  • 126
  • 207
  • 1
    Bit confused, do you want to use boolean, and then depending on input from the user, set it to true or false? Or do you want to have a item that can be set to yes or not? – dann.dev Dec 12 '11 at 20:27

7 Answers7

11

assuming input is your string:

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

Jonathon Faust
  • 12,396
  • 4
  • 50
  • 63
Colby
  • 459
  • 3
  • 9
3

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

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
1

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

String a = "foo";
String b = "bar";
boolean c = a.equals(b);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

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

if(response.equals("yes")){
 answer = true;
}else{
 answer = false;
}
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Travis J
  • 81,153
  • 41
  • 202
  • 273
0
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;
}
litterbugkid
  • 3,534
  • 7
  • 36
  • 54
0

This should do it:

boolean answer;
String input = "yes"
if (input.equals("yes")) {
   answer = true;
}
Jeff Olson
  • 6,323
  • 2
  • 22
  • 26
  • 3
    Why is everybody setting the value of a `boolean` by performing an `if` conditional on a `boolean`? – Oliver Charlesworth Dec 12 '11 at 20:32
  • Good point, although sometimes readability is important, too. And it's also possible you'd want to do other things if the input was "yes", as well, meaning an 'if' block would be more appropriate. – Jeff Olson Dec 12 '11 at 20:56
0
boolean answer = new Scanner(System.in).nextLine().equalsIgnoreCase("yes");
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417