【问题标题】:How do I declare a variable to store information from another variable that is inside of a For loop?如何声明一个变量以存储来自 For 循环内的另一个变量的信息?
【发布时间】:2021-11-21 12:57:45
【问题描述】:

尝试从用户获取字符串输入并打印每个字符的 ascii 数字,然后将这些数字添加到另一组整数和双精度数中。在循环内创建了一个 char 变量来存储 ascii 值,但对如何声明另一个变量以将其存储在循环之外感到困惑,以便我可以将这些值添加到其他数字中。

System.out.println("Please enter a String: ");
String stringInput = st.nextLine();
        
for(int i =0;i<stringInput.length(); i++)
{        
    char x = stringInput.charAt(i);
    int charCastedToInt = (int) x;

    System.out.println(charCastedToInt);
}

【问题讨论】:

  • 只需在循环内“将这些数字添加到另一组整数和双精度数”。如果您分享有关这些其他人物的详细信息(和代码)会更容易为您提供帮助。

标签: java for-loop


【解决方案1】:

没什么复杂的:

int[] chars = new int[stringInput.length()];
Set<Integer> charSet = new HashSet<>();
List<Integer> charList = new ArrayList<>();

for (int i = 0; i < stringInput.length(); i++) {        
    char x = stringInput.charAt(i);
    int charCastedToInt = (int) x;

    chars[i] = charCastedToInt;
    charSet.add(charCastedToInt);
    charList.add(charCastedToInt);

    System.out.println(charCastedToInt);
}

这里不需要演员(int)

Object 类Integer 包装了基本类型int,并且是ListSet 和其他参数化类/接口所必需的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 2012-10-15
    • 1970-01-01
    • 2021-11-26
    • 2017-07-25
    • 2013-12-04
    相关资源
    最近更新 更多