简体   繁体   中英

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. 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.

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.

The Object class Integer wraps the primitive type int , and is needed for List , Set and other parametrized classes/interfaces.

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