我已经被困了很长一段时间了。我需要忽略输入的数字、空格和特殊字符,例如 $^%##&!并使用Character.isDigit和Character.isLetter读取其他字母a-z..我尝试过使用这两种方法,但对我来说不起作用..请建议..
错误:
正常输出(不含空格和数字):
即使我输入 123$@GetLoan,预期输出也应该是 438-5626.. 他们应该忽略前几个字符“123$@”并只读 GetLoan..
完整问题:编写一个程序,提示用户输入以字母表示的电话号码,并输出相应的以数字表示的电话号码。如果用户输入超过七个字母,则仅处理前七个字母。还要在第三位数字后输出 –(连字符)。允许用户同时使用大写和小写字母以及单词之间的空格。
public class Question3 {
public static void main(String[] args) {
String letters;
char phoneDigit;
Scanner kb = new Scanner(System.in);
System.out.println("Enter letters : ");
letters = kb.next();
for (int i = 0; i < 7; i++) {
phoneDigit = letters.charAt(i);
if (Character.isLetter(phoneDigit) == true) {
if (i == 3) {
System.out.println("-");
} //If
if (phoneDigit >= 'A' && phoneDigit <= 'C'
|| phoneDigit >= 'a' && phoneDigit <= 'c') {
System.out.println("2");
} else if (phoneDigit >= 'D' && phoneDigit <= 'F'
|| phoneDigit >= 'd' && phoneDigit <= 'f') {
System.out.println("3");
} else if (phoneDigit >= 'G' && phoneDigit <= 'I'
|| phoneDigit >= 'g' && phoneDigit <= 'i') {
System.out.println("4");
} else if (phoneDigit >= 'J' && phoneDigit <= 'L'
|| phoneDigit >= 'j' && phoneDigit <= 'l') {
System.out.println("5");
} else if (phoneDigit >= 'M' && phoneDigit <= 'O'
|| phoneDigit >= 'm' && phoneDigit <= 'o') {
System.out.println("6");
} else if (phoneDigit >= 'P' && phoneDigit <= 'S'
|| phoneDigit >= 'p' && phoneDigit <= 's') {
System.out.println("7");
} else if (phoneDigit >= 'T' && phoneDigit <= 'V'
|| phoneDigit >= 't' && phoneDigit <= 'v') {
System.out.println("8");
} else if (phoneDigit >= 'W' && phoneDigit <= 'Z'
|| phoneDigit >= 'W' && phoneDigit <= 'z') {
System.out.println("9");
} // If
} // If
} // For loop
} //PSVM
最佳答案
下面的片段可能是问题所在:
for (int i = 0; i < 7; i++) {
phoneDigit = letters.charAt(i);
if (Character.isLetter(phoneDigit) == true) {
您将获取前 7 个字符,并仅打印字母字符。因此,对于输入字符串123getloan
,您将迭代123getl
,然后isLetter
将拒绝123
,因此您的程序稍后仅处理 getl
。
要迭代 7 个字母,仅当给定字符是字母时,您才需要将其更改为递增 i
,例如通过执行以下操作:
int i = 0;
for (char phoneDigit : letters.toCharArray()) {
if (Character.isLetter(phoneDigit)) {
i++;
// other ifs here
if (i == 3) {
System.out.println("-");
}
}
if (i >= 7) {
break;
}
}
编辑:修复了@Andreas提到的问题
关于java - 使用Character.isLetter和Character.isDigit忽略数字、空格并读取字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37893595/