[英]How to limit the EditText input only allow 3 digits of number either integer or decimal
[英]how to allow integer only AND not allowing more than 9 digits
System.out.println("Enter your phone number: ");
while(in.hasNextLong()) {
long phone = in.nextLong();
if(in.hasNextLong()) {
if(phone < 1000000000) {
System.out.println("Phone number: "+phone);
}
} else if(!in.hasNextInt()) {
System.out.println("Please enter a valid phone number: ");
} else if (phone < 1000000000) {
System.out.println("Please enter a valid phone number: ");
}
尝试了另一种方式
boolean valid;
long phone;
do {
System.out.println("Enter your phone number: ");
if(!in.hasNextLong()) {
phone =in.nextLong();
if(phone > 1000000000) {
System.out.println("Please enter a valid phone number");
in.nextLong();
valid=false;
}
}
}while(valid=false);
System.out.println("Phone: " + phone);
如您所见,它根本不起作用,特别是如果您输入非 integer 并且它要求输入两次,我很抱歉它一团糟
编辑:好的,有没有不使用正则表达式的方法? 我的讲师还没有教过它,所以我不确定我是否允许使用正则表达式
你需要使用正则表达式。 看看https://www.w3schools.com/java/java_regex.asp
并沿线尝试一些东西......
...
final boolean isValid = inputValue.match(^[0-9]{1,9}?) // 1 to 9 digits
if (isValid) {
...
}
...
我建议这样做:
System.out.println("Enter your phone number: ");
int phone;
for (;;) { // forever loop
String line = in.nextLine();
if (line.matches("[0-9]{1,9}")) {
phone = Integer.parseInt(line);
break;
}
System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: "+phone);
这是我不使用正则表达式的方法
System.out.println("Enter your phone number: ");
int phone;
int index = 0;
while(true) {
String line = in.nextLine();
if (valid(line)){
phone = Integer.parseInt(line);
break;
}
System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: " + phone);
和valid()
方法
boolean valid(String line){
if(line.length() > 9) return false;
for(int i = 0; i < line.length(); i++){
boolean isValid = false;
for(int asciiCode = 48; asciiCode <= 57 && !isValid; asciiCode++){
//48 is the numerical representation of the character 0
// ...
//57 is the numerical representation of the character 9
//see ASCII table
if((int)line.charAt(i) == asciiCode){
isValid = true;
}
}
if(!isValid) return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.