Skip to content

Instantly share code, notes, and snippets.

@AliLtRP
Last active Aug 28, 2022
Embed
What would you like to do?
How to convert a string into the sum of ASCII values? in java, OOP
public class main {
public static void main(String[] args) {
Ascii a = new Ascii(); //make an object
a.setS("An example"); // the string we want to get the sum of it in asii
a.asciValue(a.getS()); // pass the string as argument
a.print(); // print the result
}
}
class Ascii{
private String s;
int result =0;
// encapsulation
public void setS(String val) {
this.s = val;
}
public String getS() {
return s;
}
// method to calc. the sum of string in ascii
public int asciValue(String a) {
char[] c = a.toCharArray(); // convert the string to array of chars
for (char i: c) {
result+= (int) i; // convert each char to it's value in ascii
}
eturn result;
}
// method to print the result
// you can get rid of it
public void print() {
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment