You Can Try This:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
char[] ascii1 = testi.toCharArray();
for(char ch:ascii1){
System.out.println((int)ch+" ");
}
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
char[] ascii2 = testi2.toCharArray();
for(char ch:ascii2){
System.out.println((int)ch+" ");
}
scan.close();
}
Answer from AsSiDe on Stack OverflowYou Can Try This:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
char[] ascii1 = testi.toCharArray();
for(char ch:ascii1){
System.out.println((int)ch+" ");
}
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
char[] ascii2 = testi2.toCharArray();
for(char ch:ascii2){
System.out.println((int)ch+" ");
}
scan.close();
}
Achieve the same in a concise way by employing Java 8's lambda function. From your comment (at the accepted answer) you need the sum of the characters at the end?
String str = "name";
int sum = str.chars().reduce(0, Integer::sum);
Quick help on converting String to Ascii then back to String.
How to convert string to an ascii? - Oracle Forums
string - Convert character to ASCII numeric value in java - Stack Overflow
Character to ASCII
Videos
beginner here making a simple encoder. I need to convert the characters of a string to their ascii values, add one, and then convert it back to a string.
so lets say the string is userInput and it is abc, I need it to change abc to its ascii value, then add one, and finally send it back into the userInput string as bcd.
Very simple. Just cast your char as an int.
char character = 'a';
int ascii = (int) character;
In your case, you need to get the specific Character from the String first and then cast it.
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
Though cast is not required explicitly, but its improves readability.
int ascii = character; // Even this will do the trick.
just a different approach
String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");
bytes[0] will represent ascii of a.. and thus the other characters in the whole array.