繁体   English   中英

JAVA-如何为用户输入设置输入范围验证

[英]JAVA - how to set input range validation for user input

    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 and catch异常?

我将使用略有不同的方法。 使用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 and catch异常?

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

方法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.  

  }
}

如果要在用户输入中检查字符的校验数,请尝试这种方式。

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM