[英]Filtering java.util.Scanner input?
我正在使用java.util.Scanner
,如果超出范围,我想过滤掉用户输入,例如只接受0、1、2或3。也许像这样:
if !(sc.hasNextInt 0,1,2,3
我知道这不是有效的语法,但我想说明一下我要做什么。 如何告诉Java不要存储不符合我的条件的用户输入?
这是您必须自己实施的事情- Scanner
支持的事情。 一种典型的方法是进行这样的循环:
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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.