2016-11-25 39 views
1

就像標題我有在Java中的方法,我寫了一個問題說明。這是代碼:方法返回int,而不是字符的java中

public static char shift(char c, int k) { 

    int x = c; 

    int d = c - 65 + k; 
    int e = c - 97 + k; 

    if (x > 64 && x < 91 && d >= 0) { 

     c = (char) (d % 26 + 65); 

    } else if (x > 96 && x < 123 && e >= 0) { 

     c = (char) (e % 26 + 97); 
    } 


    if (x > 64 && x < 91 && d < 0) { 

     c = (char) ((d + 26) % 26 + 65); 

    } else if (x > 96 && x < 123 && e < 0) { 

     c = (char) ((e + 26) % 26 + 97); 
    } 

    return c; 
} 

我想轉移字母表中的字母。代碼工作完美,如果我這樣使用它(凱撒Chiper):

String s = " "; 
    String text = readString(); 
    int k = read(); 

    for (int i = 0; i < text.length(); i++) { 

     char a = text.charAt(i); 
     int c = a; 

     int d = a - 65 + k; 
     int e = a - 97 + k; 

     if (c > 64 && c < 91 && d >= 0) { 

      a = (char) (d % 26 + 65); 

     } else if (c > 96 && c < 123 && e >= 0) { 

      a = (char) (e % 26 + 97); 
     } 
      if (c > 64 && c < 91 && d < 0) { 

      a = (char) ((d + 26) % 26 + 65); 

     } else if (c > 96 && c < 123 && e < 0) { 

      a = (char) ((e + 26) % 26 + 97); 
     } 

     s += a; 
    } 

    System.out.println(s); 
} 

我不明白爲什麼該方法轉變返回時,我使用這樣的整數:轉變(「C」,5);它返回104,這是h的十進制數。我是一個java初學者和一個慢人。

預先感謝您。

+1

char是一個int tooo –

+0

你是如何使用shift()的返回值的? –

+0

我知道,但我想該方法返回一個字符。如果我寫:char a = shift('c',5); 的System.out.println(一);它顯示我104而不是'h'。 – Ralu

回答

0

你的錯誤是,你可能會增加兩個字符的統一碼。 如果你做這樣的事會發生這種情況:

System.out.println('b' + 'a'); 

或在您的情況

System.out.println(shift('c', 5) + 'a'); 

要獲得期望的結果,焦炭打印前轉換爲字符串:

String result = Character.toString(shift('c', 5)); 
System.out.println(result + 'a'); 

System.out.println(shift('c', 5) + "a");