You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何声明外部变量存储For循环内部变量的ASCII值以进行后续运算

你在循环内部声明的变量属于局部变量,作用域仅局限在循环体内部,循环结束后就会被回收,所以只需要把用于存储ASCII值的变量/容器声明在循环外部即可,下面分两种常见需求给出实现:

场景1:仅需要累计所有ASCII值的总和,直接用于后续求和运算

如果不需要单独保留每个字符的ASCII值,直接在循环外声明一个累加变量即可,因为后续要和双精度浮点数相加,建议直接声明为double类型避免精度丢失:

System.out.println("Please enter a String: ");
String stringInput = st.nextLine();
// 循环外声明累加变量,初始值设为0
double asciiTotal = 0;
        
for(int i =0;i<stringInput.length(); i++)
{        
    char x = stringInput.charAt(i);
    int charCastedToInt = (int) x;
    // 循环内将当前字符的ASCII值累加到总和变量中
    asciiTotal += charCastedToInt;
    System.out.println(charCastedToInt);
}

// 后续直接调用asciiTotal和其他数值相加即可,示例:
int otherInt = 256;
double otherDouble = 123.45;
double finalSum = asciiTotal + otherInt + otherDouble;
System.out.println("最终求和结果:" + finalSum);

场景2:需要保留每个字符的ASCII值,后续可单独调用再求和

如果后续需要用到单个字符的ASCII值做其他运算,可以在循环外声明一个数组或者集合存储所有数值:

System.out.println("Please enter a String: ");
String stringInput = st.nextLine();
// 循环外声明存储ASCII值的数组,长度和输入字符串长度一致
int[] asciiArray = new int[stringInput.length()];
        
for(int i =0;i<stringInput.length(); i++)
{        
    char x = stringInput.charAt(i);
    int charCastedToInt = (int) x;
    // 将当前ASCII值存入数组对应下标位置
    asciiArray[i] = charCastedToInt;
    System.out.println(charCastedToInt);
}

// 后续需要求和时遍历数组累加即可,示例:
double asciiTotal = 0;
for (int asciiVal : asciiArray) {
    asciiTotal += asciiVal;
}
int otherInt = 256;
double otherDouble = 123.45;
double finalSum = asciiTotal + otherInt + otherDouble;
System.out.println("最终求和结果:" + finalSum);

内容的提问来源于stack exchange,提问作者Eoin O Hagan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:06:03