简体   繁体   English

如何声明一个变量以存储来自 For 循环内的另一个变量的信息?

[英]How do I declare a variable to store information from another variable that is inside of a For loop?

Attempting to take a string input from user and print the ascii numbers of each character and then add these numbers to another set of integers and doubles.尝试从用户获取字符串输入并打印每个字符的 ascii 数字,然后将这些数字添加到另一组整数和双精度数中。 Created a char variable inside the loop to store the ascii values but confused on how I declare another variable to store this outside of the loop so I can add these values to the other figures.在循环内创建了一个 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);
}

Nothing sophisticated:没什么复杂的:

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

The cast (int) is not needed here.这里不需要强制转换(int)

The Object class Integer wraps the primitive type int , and is needed for List , Set and other parametrized classes/interfaces. Object class Integer包装了原始类型int ,并且是ListSet和其他参数化类/接口所必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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