java - If-else statements, always running -


i working on making coffee ordering system. takes inputs users , calculates price of coffee. 1 of inputs asked "syrupshots". code makes syrupshots = 3 if user chose number according size of coffee.

//if size == tall   syrup shots <=3 if(size == 1 && syrupshots < 1 || syrupshots > 3) {     syrupshots = 3; } //else if size == medium     syrup shots <=5 else if(size == 2 && syrupshots < 1 || syrupshots > 5) {     syrupshots = 3; } //else if size == venti        syrup shots <=7 else if(size == 3 && syrupshots < 1 || syrupshots > 7) {     syrupshots = 3; } system.out.println(syrupshots); 

i not sure why syrupshots = 3 no matter what.

not always, returns 1 or 2. never >3, looks should.

your problem logical operator precedence. example:

if(size == 1 && syrupshots < 1 || syrupshots > 3) {} 

if size=3 , syrupshots=5 (a valid combination), if block still entered because && evaluated first:

size == 1 && syrupshots < 1 

and equals false, have left (false || syrupshots > 3)

but || evaluated, syrupshots > 3 true, whole expression true

you need change order of precedence using brackets:

if(size == 1 && (syrupshots < 1 || syrupshots > 3)) {} 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -