+ 1

Loop

how to re-prompt a user for input after invalid data entered.. using while and if loop

17th Sep 2017, 3:29 PM
Challiebenz
Challiebenz - avatar
2 Answers
+ 7
Suppose you only want to accept positive integer. Then the following loop will keep running until it gets a positive number. Scanner scan = new Scanner (System.in); int a; while(true){ a = scan.nextInt(); if(a>0){ // or other valid condition break; } else{ System.out.println("Try again!") ; } }
17th Sep 2017, 3:44 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 3
If you have limited number of valid options- while(true) { var sport = prompt("What sport do you play? (Baseball, Football or Soccer)").toLowerCase (); if (sport =="baseball" ll sport =="football" ll sport=="soccer") //take to next screen else alert("Please enter a valid sport"); }
17th Sep 2017, 3:42 PM
Apoorva Shenoy Nayak
Apoorva Shenoy Nayak - avatar