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

标签 java

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

最佳答案

我将使用稍微不同的方法。首先使用 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 个字符。

<小时/>

Should I create a variable of the input and then list in the while loop? or should I use the try and catch exception?

我想说异常处理用于处理您不希望发生的异常情况。因此,您不应该使用 try-catch block 来处理验证。使用 do-whilewhile 循环就足够了。

关于JAVA-如何设置用户输入的输入范围验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35370811/

相关文章:

java - Spring-Data-Jpa:带子查询的内部连接

添加元素时自动对元素进行排序的 Java 列表

java - 将 WS-Security 应用于原始 SOAP 负载

java - 在 Eclipse 中链接到生成的 Java protobuf 代码

java - 从 Java 程序中获取局部变量的名称和类型

java - 在 Java 中实现神经网络 : Training and Backpropagation issues

Java进程通知Node事件循环

Java 文件复制和打开新的 jFrame

java - 如何将 Activity.class(this) 传递给方法? (安卓)

java - 带引号的东西在 Java 中似乎不起作用