+ 1
Loop
how to re-prompt a user for input after invalid data entered.. using while and if loop
2 Respostas
+ 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!") ;
}
}
+ 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");
}