JAVA - how to set input range validation for user input

时间:2016-02-12 19:33:40

标签: 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");
      }  
  }

I am trying to get user Input of the Scanner 'AccountIn' to be greater than 0 and less than 9 how can I do this? Should I create a variable of the input and then list in the while loop? or should I use the try and catch exception?

3 个答案:

答案 0 :(得分:1)

I will use a slightly different approach. Use a do-while loop to validate the input first. If input passes the check from the validation loop, proceed to add to list:

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"

Note: Since you wanted to validate your account number, it should not only check it has 0 to 9 characters. Instead, it should probably check that is has exactly 9 characters.


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

I would say Exception handling are used for handling exceptional cases where you don't expect to occur. Hence you should not be using a try-catch block to handle your validation. Using a do-while or while loop is suitable and suffice.

答案 1 :(得分:0)

The method hasNextLine() return only a boolean like in the javadoc (https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine%28%29)

To get the actual value, you must use nextLine() or nextInt()

Try something like:

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

  }
}

答案 2 :(得分:0)

If you want the check number of charaters in the user's input try this way.

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