我正在测试以查看用户输入的字符串是否是有效的电话号码,但可以得到
“字符串索引超出范围:1”
每当我尝试运行该程序时。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String number = "";
boolean d1 = Character.isDigit(number.charAt(1));
boolean d2 = Character.isDigit(number.charAt(2));
boolean d3 = Character.isDigit(number.charAt(3));
boolean d5 = Character.isDigit(number.charAt(5));
boolean d6 = Character.isDigit(number.charAt(6));
boolean d7 = Character.isDigit(number.charAt(7));
boolean d9 = Character.isDigit(number.charAt(9));
boolean d10 = Character.isDigit(number.charAt(10));
boolean d11 = Character.isDigit(number.charAt(11));
boolean d12 = Character.isDigit(number.charAt(12));
System.out.println("Please enter a phone number (ddd)ddd-dddd :");
number = sc.nextLine();
if ((number.length() == 13) && (number.charAt(0)=='(') && (number.charAt(4)==')') && (number.charAt(8)=='-') && (d1==true) && (d2==true) && (d3==true) && (d5==true) && (d6==true) && (d7==true) && (d9==true) && (d10==true) && (d11==true) && (d12==true)){
System.out.println(number + " Is a valid phone number!");
}
else {
System.out.println(number + " Is not a valid phone number!");
}
sc.close();
}
}
这也是我的第一篇文章,如果它太乱了,就对不起。
答案 0 :(得分:4)
在此代码中:
String number = "";
boolean d1 = Character.isDigit(number.charAt(1));
您正在将number
初始化为空字符串,并在下一行尝试获取该字符串的第二个字符(请记住-Java中的索引从0
开始,而不是{{1} }。
可能最简单的解决方法是移动这两行:
1
在System.out.println("Please enter a phone number (ddd)ddd-dddd :");
number = sc.nextLine();
行之后,如下所示:
String number = "";
请注意,如果在提示时输入的电话号码不够长,此操作仍将失败。在尝试完全调用String number = "";
System.out.println("Please enter a phone number (ddd)ddd-dddd :");
number = sc.nextLine();
boolean d1 = Character.isDigit(number.charAt(1));
...
之前,您可能应该验证您的字符串足够长。
答案 1 :(得分:1)
问题是您正在使用number
中的值实例化Scanner
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String number;
System.out.println("Please enter a phone number (ddd)ddd-dddd :");
number = sc.nextLine();
boolean d1 = Character.isDigit(number.charAt(1));
boolean d2 = Character.isDigit(number.charAt(2));
boolean d3 = Character.isDigit(number.charAt(3));
boolean d5 = Character.isDigit(number.charAt(5));
boolean d6 = Character.isDigit(number.charAt(6));
boolean d7 = Character.isDigit(number.charAt(7));
boolean d9 = Character.isDigit(number.charAt(9));
boolean d10 = Character.isDigit(number.charAt(10));
boolean d11 = Character.isDigit(number.charAt(11));
boolean d12 = Character.isDigit(number.charAt(12));
if ((number.length() == 13) && (number.charAt(0)=='(') && (number.charAt(4)==')') && (number.charAt(8)=='-') && (d1==true) && (d2==true) && (d3==true) && (d5==true) && (d6==true) && (d7==true) && (d9==true) && (d10==true) && (d11==true) && (d12==true)){
System.out.println(number + " Is a valid phone number!");
}
else {
System.out.println(number + " Is not a valid phone number!");
}
sc.close();
}
尽管有更好的方法来检查电话号码,但是为了解决您的问题,我们将number
变量的初始值设置为用户输入的值。然后我们可以在正确初始化Boolean
之后执行number
检查。
您之前的问题是您尝试执行number.chatAt(1)
等等,因为值为""
时没有值1