How to run scanner first in a if-else statement before execute the rest of the code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 2

How to run scanner first in a if-else statement before execute the rest of the code?

Hi, i would like to create program to let user to choose option 1 or 2 or 3, then depends on the options selected and it might ask user to key in diff info(for example, option 1 ask age, option 2 ask name and etc). But currently the issue is that after user have selected option, it will run the code inside that option(if else statment) before my scanner ( which means my scanner run last). May i know how to solve this issue? public class Program { public static void main(String[] args) { Scanner ans =new Scanner(System.in); System.out.println("Please select 1 or 2 or 3"); String customer_ans = ans.nextLine(); int age; if(customer_ans == "1") { System.out.prinln("Your age:"); age = ans.nextInt() System.out.printf("Your agr is%d", age); } else if(customer_ans == "2") { .... } else { .... } } }

13th Apr 2022, 2:44 AM
Jacky
3 Answers
+ 2
Use equals method for string comparisions, like : (instead of ==) if( customer_ans.equals("1") ) Instead you can take integers as input..!!? Scanner is class, through object of it, we can accept input.. Hope it helps..
13th Apr 2022, 11:53 AM
Jayakrishna 🇮🇳
+ 2
https://www.sololearn.com/discuss/3016143/?ref=app 🙄 Same answer... Use String equals() méthode. Your scanner run before the statments, but if statment is Always false with == (== compare the ref of the object, his identity, scanner make a new String object)
13th Apr 2022, 6:58 PM
Roland
Roland - avatar
0
I'm not sure what you mean. How can a user select an option if the scanner happens later? Do you mean in the app? Can you add the code from the code playground?
13th Apr 2022, 3:46 AM
Ausgrindtube
Ausgrindtube - avatar