在for循环中添加到ASCII代码 [英] Adding to ascii code during for loop

查看:100
本文介绍了在for循环中添加到ASCII代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的修复程序,但我似乎无法解决.

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

我正在尝试在for循环中向字符的ascii值添加一个整数.

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?

这是代码:

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

sentence.charAt(i) += (char)x;行对我不起作用

推荐答案

简单:

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

您错误地认为charAt()给您带来了左手侧"的麻烦.换句话说:您可以分配一个值的东西;像一个变量.

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.

但这是不可能的:charAt()返回一个char值;表示该索引处字符串中的char.

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

它确实为您提供了一些使您可以操纵字符串本身的东西!字符串是不可变的.您不能使用charAt()修改其内容!

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

但是您不能使用charAt()来达到相同的效果!

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

因此,为了使代码正常工作,您必须构建一个 new 字符串,例如:

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!)

除此之外:我找到了该方法的名称;以及它如何处理该布尔字段...有点令人困惑.您会发现,如果加密为 true ... ...该方法没有执行任何操作?!然后,它不会切换"任何内容.因此,这个名字确实令人误解.与您的代码不匹配!

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!

这篇关于在for循环中添加到ASCII代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆