How to convert a string into the sum of ASCII values? in java, OOP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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