[英]Java: Converting letters to digits on a phone keypad
我正在为一个班级分配作业,我需要将用户输入的字母转换为电话上的数字。 像A=2
或K=5
。 我将用户输入转换为大写,然后转换为ASCII。 我在我的if / else中使用ASCII,它可以编译并正常工作,但始终会打印
System.out.println (x+"'s corrosponding digit is " + 2);
无论我输入什么字母,最后一行
else System.err.println("invalid char " + x);
不起作用,它只是打印出数字2
其中x
是我输入的内容。
public class Phone {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("Please enter a letter from A-Z.");
char x = input.next().charAt(0);
x = Character.toUpperCase(x);
int y = x;
System.out.println ("You entered the letter " + x);
if (y>=65 || y<=67)
System.out.println (x+"'s corrosponding digit is " + 2);
else if (y>=68 || y<=70)
System.out.println (x+"'s corrosponding digit is " + 3);
else if (y>=71 || y<=73)
System.out.println (x+"'s corrosponding digit is " + 4);
else if (y>=74 || y<=76)
System.out.println (x+"'s corrosponding digit is " + 5);
else if (y>=77 || y<=79)
System.out.println (x+"'s corrosponding digit is " + 6);
else if (y>=80 || y<=83)
System.out.println (x+"'s corrosponding digit is " + 7);
else if (y>=84 || y<=86)
System.out.println (x+"'s corrosponding digit is " + 8);
else if (y>=87 || y<=90)
System.out.println (x+"'s corrosponding digit is " + 9);
else System.err.println("invalid char " + x);
}
}
替换|| 与&&在if else语句中。
在if块上,您的第一个条件是if (y>=65 || y<=67)
。 让我们打开一点:
IF ( y >= 65 ) OR ( y <= 67 )
。
看到问题了吗? 由于您已编写OR,因此整个语句将始终为true
:对于任何int y,y都必须大于65或小于67。我怀疑您打算编写AND( &&
)。
您的条件有误,请更改||
到&&
:
if (y>=65 && y<=67) ...
并像这样纠正所有条件。
有例子(y>=65 || y<=67)
。 这意味着该条件始终为true
,因为任何y
始终大于或等于65, 或者小于或等于67(难以解释)。 如果要检查,如果同时满足两个条件,则必须使用&&
您的第一个条件是if (y>=65 || y<=67)
并且对于任何字符,如果满足这两个条件中的任何一个,它将打印x+"'s corrosponding digit is " + 2
并且从不检查其他任何一个else if
条件。 您需要替换||
在所有情况下都可以使用&&
运算符。
为什么不这样:
char x = input.next().charAt(0);
x = Character.toUpperCase(x);
int digit = 0;
switch (x ) {
case 'A': case 'B': case 'C':
digit = 1;
break;
case 'D': case'E': case 'F':
digit = 2;
break;
//etc.
default:
break;
}
if ( digit < 1 ) {
System.out.println( "The letter " + x + " is not on a phone pad" );
} else {
System.out.println( "x + "'s corrosponding digit is " + digit);
}
请注意,某些电话可能会使用不同的字母组合。 例如,有些电话使用“ PQRS”表示7,有些使用“ PRS”,省略了Q。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.