2016-02-29 56 views
-1

我正在为班级分配工作,我需要将一封信的用户输入信息转换为电话号码。像A = 2或K = 5一样。我将用户输入转换为大写,然后转换为ASCII。我使用的ASCII为我的if/else和它编译和作品,但始终打印Java:将字母转换为电话键盘上的数字。

System.out.println (x+"'s corrosponding digit is " + 2); 

不管信我输入,也是最后一行

else System.err.println("invalid char " + x); 

不起作用,它只是打印出数字是2,x是我输入的东西。

import java.util.Scanner; 

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); 






} 

} 
+0

这不是一个MCVE。 – Raedwald

回答

1

更换||与& &在你的if else语句中。

1

在你的if块上,你的第一个条件是if (y>=65 || y<=67)。让我们打开它:

IF (y >= 65) OR (y <= 67)

您是否看到这个问题?既然你写了一个OR,整个声明总是会计算为true:对于任何int y,y必须大于65或小于67.我怀疑你打算写一个AND(&&)。

1

你有错的条件下,改变||&&

if (y>=65 && y<=67) ... 

,正确的一样,所有条件。

举例(y>=65 || y<=67)。这意味着条件总是为true,因为任何y始终大于或等于65 小于或等于67(难以解释)。如果要检查,如果这两个条件同时是真实的,你必须使用&&

1

你的第一个条件是if (y>=65 || y<=67)和任何字符,如果任何这些2个条件满足时,将打印x+"'s corrosponding digit is " + 2和从来不检查任何的其他else if条件。您需要在所有条件下将||运营商更换为&&运营商。

1

为什么不一样的东西:

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.