2016-02-12 148 views
1
public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     //Scanner for AccountNumbers 
     Scanner AccountIn = new Scanner(System.in); 
     ArrayList<String> AccountNumber = new ArrayList<String>();  
     System.out.println("Create Account Number"); 

     while(AccountIn.hasNextLine()>0 &&AccountIn.hasNextLine() < 9){  
     //EveryTime AccountNumber Is created store in Array 
     AccountNumber.add(AccountIn.nextLine());     
     money = reader.readDouble("Enter Starting Amount Of Money"); 
     } 
    } 

我想获得用户扫描仪'AccountIn'的输入大于0小于9我该怎么做?我应该创建一个输入变量,然后在while循环中列出吗?还是应该使用try和catch异常?JAVA - 如何设置用户输入的输入范围验证

+0

你想检查'AccountIn'中的章程吗? –

+0

是的。 AccountIn是用户输入账号的扫描仪。 – Ahmed

+0

@Ahmed看看我的解决方案。 – user3437460

回答

1

我会用稍微不同的方法。首先使用do-while循环验证输入。如果输入传递从确认循环检查,请添加到列表:

String input = ""; 
Scanner scn = new Scanner(System.in);  

do{ 
    System.out.print("Please enter account number:"); 
    input = scn.nextLine(); 
}while(input.length() != 9); 

accountNumbers.add(input); //Note: I write "accountNumbers" instead of "AccountNumber" 

:既然你想验证你的帐号,它不仅要检查它有0至9个字符。相反,它可能应该检查它是否只有9个字符。


我应该创建输入的while循环变量,然后列表?还是应该使用try和catch异常?

我会说异常处理用于处理您不希望发生的异常情况。因此,您不应该使用try-catch块来处理您的验证。使用do-whilewhile循环是合适和充分的。

0

的方法hasNextLine()在Javadoc只返回一个布尔像(https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine%28%29

要获得实际值,则必须使用nextLine()nextInt()

试着这么做:

while(AccountIn.hasNextLine()){  
    int accountValue = AccountIn.nextInt(); 
    if (accountValue > 0 && accountValue < 9) { 
    // Something usefull. 

    } 
} 
+0

嗨,谢谢你的回答,但我可能没有详细说明,对不起,我很抱歉,但我的意思是,如果我可能有一个用户输入字符为9 123456789而不只是一个值:)希望你明白。 – Ahmed

0

如果您希望用户输入中的charaters的检查号码以这种方式尝试。

Scanner AccountIn = new Scanner(System.in); 
ArrayList<String> AccountNumber = new ArrayList<String>(); 

System.out.println("Create Account Number"); 
String acountNumber = AccountIn.nextLine(); 

    while(acountNumber.length() < 9 && acountNumber.length() > 0){ 
     System.out.println("Account Number Should Contain 9 Numbers. Please re enter:"); 
     acountNumber = AccountIn.nextLine(); 
    }   
     AccountNumber.add(acountNumber); 
     System.out.println("Account Number Saved");