简体   繁体   English

方法在java中返回int而不是char

[英]Method returns int instead of char in java

Like stated in the title I have a problem with a method in java that I wrote. 就像标题中所说的那样,我在编写java的方法时遇到了问题。 This is the code: 这是代码:

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

I want to shift a letter in Alphabet. 我想换一个字母的字母。 The code works perfectly if I use it like this (Caesar Chiper): 如果我这样使用它(Caesar 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);
}

I don't understand why the method shift returns an integer when I use it like this: shift('c', 5); 我不明白为什么方法shift在我使用它时返回一个整数:shift('c',5); it returns 104, which is the dec number for h. 它返回104,这是h的dec数。 I'm a beginner in java and a slow person. 我是java的初学者,也是个慢人。

Thank you in advance. 先感谢您。

Your mistake is that you're probably adding the unicodes of two characters. 你的错误是你可能正在添加两个字符的unicodes。 This can happen if you do something like this: 如果您执行以下操作,就会发生这种情况:

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

or in your case 或者在你的情况下

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

To get the desired result, convert the char to a string before printing: 要获得所需的结果,请在打印前将char转换为字符串:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM