I'm using a java.util.Scanner
, and I want to filter out user input if it is out of range, for example only accept 0, 1, 2 or 3. Perhaps something like:
if !(sc.hasNextInt 0,1,2,3
I'm aware this isn't valid syntax, but I wanted to show what I was going for. How do I tell Java not to store user input that doesn't meet my criteria?
This is something you have to implement yourself -- it's not something Scanner
supports. A typical way is to have some sort of loop like this:
int input;
do {
input = sc.nextInt();
} while (input < 0 || input > 3);
public class Test1
{
public static void main(String [] args)
{
List<Integer> lst= new ArrayList<Integer>();
//Take user input any number of times based on your condition.
System.out.println("Please enter a number :");
Scanner sc= new Scanner(System.in);
int i= sc.nextInt();
if(i==0 || i==1 || i==2 ||i==3)
{
lst.add(i);
}
//Go back
}
}
public static void main(String[] args) throws AWTException, Exception {
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt())
{ int val= sc.nextInt();
if(val==0||val==1 || val==2||val==3)
{
// your code here
}
else
{
System.out.println("wrong number, enter again");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.