Find the summation of the numbers for your name when a=1, b=2,...z=26
such as johnsmith = 116
package Test;
import java.util.ArrayList;
public class numSumForName{
public static void main(String[] args) {
ArrayList<Integer> alist = new ArrayList<>(); //add numbers 1 to 26
ArrayList<String> blist = new ArrayList<>(); //add a to z
ArrayList<String> clist = new ArrayList<>(); // get the name
ArrayList<Integer> dlist = new ArrayList<>(); // get the corresponding numbers
blist.add("a");
blist.add("b");
blist.add("c");
blist.add("d");
blist.add("e");
blist.add("f");
blist.add("g");
blist.add("h");
blist.add("i");
blist.add("j");
blist.add("k");
blist.add("l");
blist.add("m");
blist.add("n");
blist.add("o");
blist.add("p");
blist.add("q");
blist.add("r");
blist.add("s");
blist.add("t");
blist.add("u");
blist.add("v");
blist.add("w");
blist.add("x");
blist.add("y");
blist.add("z");
System.out.println("blist is "+blist);//[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
String name = "johnsmith";
for(int i=0;i<26;i++) {
alist.add(i+1);
}
System.out.println("alist is "+alist);//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
String nameChar;
int nameLength = name.length();
for(int j=0;j<nameLength;j++) {
nameChar = Character.toString(name.charAt(j));
for(int x=0;x<26;x++) {
String aTozChar = blist.get(x);
if(nameChar.equals(aTozChar)){
clist.add(nameChar);
dlist.add((blist.indexOf(aTozChar))+1);
}
}
}
System.out.println("clist is "+clist);//[j, o, h, n, s, m, i, t, h]
System.out.println("dlist is "+dlist);//[10, 15, 8, 14, 19, 13, 9, 20, 8]
int summation=0;
for(int y=0;y<nameLength;y++) {
summation = summation+dlist.get(y);
}
System.out.println("The summation of the chars " +summation);//116
}
}
Output:
blist is [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
alist is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
clist is [j, o, h, n, s, m, i, t, h]
dlist is [10, 15, 8, 14, 19, 13, 9, 20, 8]
The summation of the chars 116
No comments:
Post a Comment