【发布时间】:2021-02-07 03:43:11
【问题描述】:
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);
你可以看到它根本不起作用,特别是如果你输入一个非整数并且它要求输入两次我很抱歉它一团糟
编辑:好的,有没有不使用正则表达式的方法?我的讲师还没有教过它,所以我不确定我是否允许使用正则表达式
【问题讨论】:
-
请注意,您的 'while (valid=false)' 将永远无法工作,因为您使用的是单个 '=' 。使用单个“=”,您将值“假”分配给变量“有效”。您要做的是检查值,这是通过'while(valid == false)'实现的,可以简化为'while(!valid)'。
-
电话号码就是号码是一种误解。它实际上是一串数字。当电话号码以 0 开头时,您可以识别差异。最好在程序中将它们表示为字符串。
标签: java if-statement while-loop integer do-while