简体   繁体   中英

Conversion of ASCII code to Character doesn't work

First, i'm beginner in Android development. I would like to know why my app crashes when i try to convert ASCII code to Character.

private String crip(String str, String psw) {
    int code = 0;
    String full_word="";
    for (int i= 0; i <= str.length(); i++) {
        code=(int)str.charAt(i); // Crashes here (I guess)
        full_word+=code;
    }
    return full_word;
}

And on the onClick event:

crip.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!psw.getText().toString().isEmpty() && !str.getText().toString().isEmpty()) {
            out.setText(crip(str.getText().toString(), psw.getText().toString()));
        }

    }
});

There is something wrong?

Remember everything in java is zero indexed. So a string that has 3 characters has characters at 0,1 and 2

However your code accesses chars (assuming a str length of 3) at 0,1,2 & 3

   for (int i= 0; i <= str.length(); i++) {
        code=(int)str.charAt(i); 
        .....

So you should end your loop 1 earlier or

   for (int i= 0; i < str.length(); i++) {
        code=(int)str.charAt(i); 
        .....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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