我使用的是java.util.Scanner,如果用户输入超出范围,我想过滤掉它,例如只接受0、1、2或3。可能是这样的:
if !(sc.hasNextInt 0,1,2,3我知道这不是有效的语法,但我想说明我要做的是什么。如何告诉Java不要存储不符合我的标准的用户输入?
发布于 2013-12-30 15:14:59
这是您必须自己实现的东西--这不是Scanner支持的东西。一种典型的方法是使用如下所示的某种循环:
int input;
do {
input = sc.nextInt();
} while (input < 0 || input > 3);发布于 2013-12-30 15:17:01
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
}
}发布于 2013-12-30 15:14:38
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");
}
}
}https://stackoverflow.com/questions/20834913
复制相似问题