3 Replies Latest reply on Mar 2, 2008 6:05 AM by 807591

    Converting chars to ints, get a strange math error...

    807591
      Here's the code I have.
      import java.util.*;
      
      public class Encryption {
      
           public static void main(String[] args) {
                
                Scanner sc1 = new Scanner(System.in);
                System.out.print("Enter a four-digit integer to be encrypted: ");
                String encrypt = sc1.nextLine();
                
                char a = encrypt.charAt(0);
                char b = encrypt.charAt(1);
                char c = encrypt.charAt(2);
                char d = encrypt.charAt(3);
                
                int as = new Integer(a).intValue();
                int bs = new Integer(b).intValue();
                int cs = new Integer(c).intValue();
                int ds = new Integer(d).intValue();
                
                int codea = (as + 7);
                while (codea > 9) {codea = codea - 10;}
                int codeb = (bs + 7);
                while (codeb > 9) {codeb = codeb - 10;}
                int codec = (cs + 7);
                while (codec > 9) {codec = codec - 10;}
                int coded = (ds + 7);
                while (coded > 9) {coded = coded - 10;}
                
                int finala = codec;
                int finalb = coded;
                int finalc = codea;
                int finald = codeb;
                
                String encrypted = ("" + finala + "" + finalb + "" + finalc + "" + finald + "");
                
                //System.out.println ("The encrypted number is " + encrypted + ""); set aside while debugging
                
                System.out.println(" " + a + " " + b + " " + c + " " + d + " ");
                System.out.println(" " + as + " " + bs + " " + cs + " " + ds + " ");
      
           }
      
      }
      Now here's the console.

      Enter a four-digit integer to be encrypted: 1234
      1 2 3 4
      49 50 51 52

      When I went from char to int, 1 became 49, 2 became 50, etc...how did this happen?