add number to a character to make it another character

有些话、适合烂在心里 提交于 2019-12-12 01:22:27

问题


I want to have a char, add number to it and get another char(a+2=c)

    int leng,leng2;
    String word = "";
    String key = "";
    String enc ="";
    char x;
    char z;
    char tost;
    System.out.println("gimme word");
    word=in.next();
    System.out.println("gimme key");
    key=in.next();
    leng=word.length();
    leng2=key.length();

    for(int i=1;i<=leng;i++)
    {
        z=word.charAt(i-1);
        x=key.charAt(i-1);
        int plus=z + x;
        tost=(char)plus;
        enc=enc+tost;
        System.out.println(enc);
        System.out.println(tost);
        System.out.println((char)z);
        System.out.println((char)x);
        System.out.println(plus);
        System.out.println((char)plus);
    }

I want it to print c and in my code I do it with charAt because I have a full string and I tried to search for many solutions, and tried myself many things, they all didnt work sadly.

edit: full code is on, as requested the way of char plus doesnt work and says it is an error


回答1:


If you want to do this for the whole string then you may use a for loop -

String r= "abc"; 
int x=2;

for(i=0; i<r.length(); i++){
  char z= r.charAt(0);  
  int plus=z+x; 
  System.out.println((char)plus);
}  

Look at the type casting at the System.out.println(). Since plus is an int you have to explicitly cast it to a char.




回答2:


You need char plus=z+x; not plus=r+x;.

That would add 2 to the character a, resulting in the character c.

You can print it with :

System.out.println(plus);



回答3:


It shouldn't even compile. You haven't declared the variable plus. Also you want to add 2 to the character at index zero of r which is stored in z. So you'll have to add x to z. Do something like this instead

String r = "abc";  
int x = 2;
char z = r.charAt(0);
char plus = z + x;
System.out.println(plus);



回答4:


Your code

String r= "abc";  
int x=2;
char z= r.charAt(0);  
plus=r+x                                       // wrong do int plus=z+x;  
String plus2=(String)String.valueOf(plus);     //not required
System.out.println(plus2);                     // plus not defined

Corrected Code

String r= "abc";  
int x=2;
char z= r.charAt(0);  
int plus=z+x;  
System.out.println((char)plus);

output

c

Demo

After your edit

change only one line

int plus=z + Character.getNumericValue(x);

Demo



来源:https://stackoverflow.com/questions/29459437/add-number-to-a-character-to-make-it-another-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!