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-while
或 while
循环就足够了。
关于JAVA-如何设置用户输入的输入范围验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35370811/