Input Handling | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Input Handling

A method from one of my projects is like :- Scanner sc = new Scanner(System.in); int hi; static void some(){ if(sc.hasNextInt()){ int inp = sc.nextInt(); if(inp == 0 || inp == 1) hi = input; } else { System.out.print("Invalid Input. Enter again :- "); some(); } } So, here I want the user to enter either 1 or 0 , or else he should get the error message, and could re-enter his input. Here's what's expected :- (Ques is a bit long, see 1st ans)

14th Oct 2017, 4:31 PM
Meharban Singh
Meharban Singh - avatar
4 Answers
+ 2
(Question Continued) if the user enter correct input, its accepted as variable input . Otherwise, an error is thrown, followed by a chance to re-enter his input. This process continues/loops until user inputs correct input. Here's what happens :- If inp is correct, it works as expected. If not, it shows the error, and recurse the method infinite times, instead of allowing user to input the correct answer. Thats because if is not true from second recuse onwards. I know that but.. How to fix it?? Any alternative?? Thanks.
14th Oct 2017, 4:37 PM
Meharban Singh
Meharban Singh - avatar
+ 2
Oops I messed up some stuff, now its corrected, thanks. Also I hv tried continue statement, it didn't work. If you could explain via editing my code, that would be appreciated. Thanks.
14th Oct 2017, 6:02 PM
Meharban Singh
Meharban Singh - avatar
0
I think u may use continue statement... try once
14th Oct 2017, 5:44 PM
Anuraj Garhwal
0
in this program u also haven't declared hi
14th Oct 2017, 5:44 PM
Anuraj Garhwal