简体   繁体   中英

Adding to ascii code during for loop

This is probably a simple fix but I can't seem to solve it.

I am trying to add an integer to the ascii value of characters during a for loop.

It is giving me the error that the program expects a variable rather than a value. How can I do what I am trying to do here?

Here is the code:

public boolean toggleEncryption(){
    if(encrypted == false){
        for(int i = 0; i < sentence.length(); i++){
            if(sentence.charAt(i) >= 65 && sentence.charAt(i) <= 90){
                int x = (int)sentence.charAt(i);
                x += key;
                while(x > 90){
                    x = x - 26;
                }
                sentence.charAt(i) += (char)x;
            }
        }
    }
    return encrypted;
}

the line sentence.charAt(i) += (char)x; is not working for me

Simple:

sentence.charAt(i) += (char)x;

You wrongly assume that charAt() gives you a "left hand side" thingy. In other words: something that you can assign a value to; like a variable.

But this is not possible: charAt() returns an char value; that represents the char within the string at that index.

It does not give you something that allows you to manipulate the string itself! Strings are immutable; you can't use charAt() to modify its content!

In other words; you can do this:

char c = 'a';
c += 'b';

but you can't use charAt() to achieve the same!

Thus, in order to make your code work, you have to build a new string, like:

StringBuilder builder = new StringBuilder(sentence.length());
for(int i = 0; i < sentence.length(); i++) {
  if(sentence.charAt(i) >= 65 && sentence.charAt(i) <= 90){
    int x = (int)sentence.charAt(i);
    x += key;
    while(x > 90){
      x = x - 26;
    }
    builder.append(sentence.charAt(i) + (char)x));
  } else {
    builder.append(sentence.charAt(i)); 
  }
}

(disclaimer: I just wrote down the above code; there might be typos or little bugs in there; it is meant to be "pseudo code" to get you going!)

Beyond that: I find the name of that method; and how it deals with that boolean field ... a bit confusing. You see, if encryption is true ... the method does nothing?! Then it doesn't "toggle" anything. Thus that name is really misleading resp. not matching what your code is doing!

Here charAt(i) returns a char:

sentence.charAt(i) += (char)x;

1) You cannot assign a character to a value but you can do it to a variable.

2) Even if you used a variable such as

char tempChar = sentence.charAt(i);

You cannot do then :

tempChar += (char)x;

As you cannot increment (+=) a character with another character.

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