Urgent: Casting int to char!!!

I want to convert integer variable that take values between 0 -10 to a char type because i am using the values to call setCharAt() method on a string buffer. But the char casting is not returning the right values. How do i achieve this?

I think you are better of by using a String because the 10 has two digits.
Make sure you import java.lang.Integer and do the following
int i;
String s = Integer.toString(i);
Of course you can easily get the char by using the charAt(int index) method of the class String.

Similar Messages

  • Int to char - char to int

    I have 2 methods.
    The first method takes an int from 0-256 and casts it to a char and then places the char in a string:
    cCryptedString [iLoop] = (char) iCryptedValue;
    The second method reads the string and casts each character from it into an int.
    iPassStringValue = (int) aString.charAt(iLoop);
    If the iCryptedValue in the 1st method is > 127 and < 150 (because that's as far as they will go at the moment), the casting of that int (i.e. 145) to a char results in a ? being placed in cCryptedString[iLoop].
    When the 2nd method reads the string and encounters the ? placed by the first method, the casting of that char to an int results in a 63 (the ascii value of a ?) instead of the original 145.
    This was not a problem until I installed and ran WebLogic 6.0 sp2 using jdk 1.3 on a Windows 2000 machine. It is working fine under WebLogic 5.1 using jdk 1.2.2.
    Any ideas?
    Thanks,
    Mark

    Here is the 1st method:
    public String encryptString(String aString) {
    int iPassStringValue = 0;
    int iEncryptKeyValue = 0;
    int iCryptedValue = 0;
    char cCryptedString [] = new char[aString.length()];
    for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
    iPassStringValue = (int) aString.charAt(iLoop);
    iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
    iCryptedValue = iPassStringValue + iEncryptKeyValue;
    if (iCryptedValue > 255)
    iCryptedValue = iCryptedValue - 256;
    cCryptedString [iLoop] = (char) iCryptedValue;
    return new String(cCryptedString);
    Here is the 2nd method:
    public String decryptString(String aString) {
    int iPassStringValue = 0;
    int iEncryptKeyValue = 0;
    int iDecryptedValue = 0;
    char cDecryptedString [] = new char[aString.length()];
    for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
    iPassStringValue = (int) aString.charAt(iLoop);
    iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
    iDecryptedValue = iPassStringValue - iEncryptKeyValue;
    if (iDecryptedValue < 0)
    iDecryptedValue = iDecryptedValue + 256;
    cDecryptedString [iLoop] = (char) iDecryptedValue;
    return new String(cDecryptedString);
    Thanks!!

  • From int to char...

    Got a nice little problem: I have an int (e.g. int i = 111). This should be transformed into the appropriate ASCII-Code char (or UNICODE-char, if only this is possible). Sounds easy but I didn't manage it.
    In desperate need for help... :-)
    Hannibal_
    Thanx!

    Have you ever tried to cast an int to char? I've tried it for hours now but I didn't get it right. There is no problem to specify a char by giving it an int value (char c = 111) but to cast an int to char. It's not possible to do it like this:
    char c;
    int i = 111;
    c = i;
    Thanx!

  • Casting Number as Char - how to hide decimal places?

    I am casting a number as a Char because I am concatenating it with other things. The problem is that when I cast to char, it displays two decimal places of just 0's. I really don't want to show the decimal place or anything after it. Is there a way to remove them?
    Thanks

    Hi,
    You can have two approaches for the same.
    1> cast( cast(column as int) as char)
    2> Go to the column properties(i.e the finger mark on the coulmn heading). Then select the data format tab and check the override the default data format tab. Then you can set the decimal places.

  • Convert from int to char

    Hi,
    How can I convert from an int to char?

    The challange is to convert from int to String without using any API or automatic conversionWoah, what a challenge ! Why ?
    Anyway, what about a recursive call and switch statement. Something likepublic String intToString(int n) {
        if(n<0) {
            return "-"+intToString(-n);
        if(n<10) {
            return getStringDigit(n);
        else {
            return intToString(n/10) + getStringDigit(n%10);
    private String getStringDigit(int n) {
        switch(n) {
            case 0:
                return "0";
            // etc.
    }

  • Typecasting int into char

    I've got a method I'm working on that looks like this:
    private static String generatePassword()
    String pass = "";
    int randomInt;
    char a;
    for(int i = 1; i <= PASSWORD_LENGTH; i++)
    randomInt = generator.nextInt();
    a = (char)randomInt;
    pass = pass + a;
    System.out.print(pass);
    return pass;
    What I'm trying to do here is create a randomly generated password that consists of five characters. Password_Length is a static variable set to 5. I'm having a problem typecasting the randomInt into a character. Everytime I do this, my display comes back as 'boxes' for each character. If anyone can help, it'd be appriciated.

    private static String generatePassword()
    String pass = "";
    int randomInt;
    char a;
    for(int i = 1; i <= PASSWORD_LENGTH; i++)
                  randomInt = (int)(((double)('z'-'a'))*java.lang.Math.random());
                  if(java.lang.Math.random()<0.5)
                      randomInt -= ('a'-'A');
    a = (char)randomInt;
    pass = pass + a;
    System.out.print(pass);
    return pass;
    }

  • Int to Char...I don't know what the problem is here

    Everything compiles fine here, and if I print out the "encryption" variable I get what looks like it would be right, converted into chars, but when I try to convert the int to char(my char variable for that is 'w'), my compiler freaks out, I don't even know what it's doing it doesn't give me an error, but sometimes it prints out nothing but sometimes it prints out "puTTypUTtypuTTYPUtty" ...why is it doing that and what is wrong with what I am doing?.
    public class encrypt
    public static void main(String[] args)
    String plainText = "hello, my name is christy.";
    String keyWord = "nice to meet you";
    int encryption = 0;
    char ch = 'a';
    char c = 'a';
    int encryptor = 0;
    int charCode;
    int sum = 0;
    char w;
    int i = plainText.length();
    int j = plainText.length();
    int[] plain = new int;
    int[] key = new int[j];
    for(i=0; i<plainText.length(); i++)
    ch = plainText.charAt(i);
    charCode = (int)ch;
    if(charCode > 97 && charCode < 122)//make lowercase
    {charCode = charCode - 97;}
    if(charCode > 65 && charCode < 90)
    {charCode = charCode - 65;}
    plain[i] = charCode;
         for(j=0; j<keyWord.length(); j++)
    c = keyWord.charAt(j);
    int chCode = (int)c;
    if(chCode > 97 && chCode < 122)
    {chCode = chCode - 97;}
    if(chCode > 65 && chCode < 90)
    {chCode = chCode - 65;}
    key[j] = chCode;
    encryption = (plain[i] + key[j]) % 26;
    w = (char)encryption;
    System.out.print(w);

    And for that matter, use increment/decrement assignment operators (like += and -=) instead of verbosely repeating the variable. And if you're going to use character-by-character case conversion, use the methods in Character don't do it like a C programmer circa 1982. And if this is anything other than a homework assignment, use encryption code provided in the JDK; don't reinvent it.

  • Necesito saber cual es la instrucion que me convierte un int a char es decir lo contrario a la instrucion atoi ya que necesito convertir el entero a cadena para utilizar ese dato en la instrucion SetCrtlval

    Necesito saber cual es la instruccion en cvi que convierte int a char

    Usa sprintf(char Destino, const char Formato, origen_de_datos), que esta en la libreria ANSI C. Es una funcion general que genera un string de chars con cualquier tipo de datos.
    Debes declarar un char Destino del largo necesario para que contenga todo el numero (aprox. 6 caracteres para un int). El char formato es del tipo "%d" para un entero
    Ej
    int Entero;
    char EnteroConvertido[6];
    sprintf(EnteroConvertido,"%d",Entero);

  • HOW can I convert int value char TO String

    I am trying to study Java by books, but sometimes it is quite difficult to find answers even to simple questions...
    I am writing a program that analyzes a Chinese text in Unicode. What I get from the text is CHAR int value (in decimals), and now I need to find them in another text file (with RegEx). But I can't find a way how to convert an INT value of a char into a String.
    Could you help me?
    Thank you in advance.

    You are confusing matters a bit. A char is a char is a char, no matter
    how you represent it. Have a look at this:char a= 'A';
    char b= 65;Both a and b have the same value. The representation of that value
    can be 'A' or 65 or even (char)('B'-1), because the decimal representation
    of 'B' is 66. Note the funny construct (char)(...). This construct casts
    the value ... back to the char type. Java performs all non-fraction
    arithmetic using four byte integers. The cast transforms it back to
    a two byte char type.
    Strings are just concatenations of zero or more chars. the charAt(i)
    method returns you the i-th char in a string. Have a look:String s= "AB";
    char a= 'A';
    char b= (char)(a+1);
    if (a == s.charAt(0)) System.out.println("yep");
    if (b == s.charAt(1)) System.out.println("yep");This piece of code prints "yep" two times. If you want to compare two
    Strings instead, you have to do this:String s= "AB";
    char a= 'A';
    char b= 'B';
    String t= ""+a+b;
    if (s.equals(t)) System.out.println("yep");Note the 'equals' method instead of the '==' operator. Also note that
    string t was constructed using those two chars. The above was a
    shorthand of something like this:StringBuffer sb= new StringBuffer("");
    sb.append(a);
    sb.append(b);
    String t= sb.toString();This is all handled by the compiler, for now, you can simply use the '+'
    operator if you want to append a char to a string. Note that it is not
    very efficient, but it'll do for now.
    Does this get your started?
    kind regards,
    Jos

  • Random int and char

    I am developing a program that generates a SIP message. For the branch tag of Via header field i need to generate random mixture of integers and strings....sth like this (89hg823Hjkg8).
    I know how to generate int and string separately....but ive no idea how to generate the mixture of two. help
    thanx in advance

    You could use java.util.Random to generate random numbers from 48 to 122 inclusive and then cast it as a char. Only problem is that several of the numbers within this range represent other characters such as ? > @ etc.

  • Int to char

    Hello,
    How can I convert an int variable representing a character to a char variable?
    Thanks.

    Nononono; you must get it straight: as everybody well
    knows the Lewis/Clark
    approach suffers from negative zeros in their one
    complement scheme; that's
    why the latest JTCAPI abondoned it in their final
    draft proposed at the JCP#56632
    sabre and I are right and you are dead wrong; so
    there :-P
    kind regards,
    JosI'll never never never never never never never believe you, no matter how many times you damn oligarchs post the truth, no matter how many times you back it up with supporting references. NA NA NA NA NA NA NA I CAN'T HEEEAAAR YOUUUU!
    World spins
    RD-R
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Error when try a "cast" in a char(13) to get a varchar....

    AVAB_Codigo it's a "char(13)", get me a error :
    "Invalid operator for data type. Operator equals boolean AND, type equals varchar."
    when i use a cast...  the error still appear,.....  what should i do ?
    -- 1st attemp --------------------------------------------------------------------
      case when (SUBSTRING(AVAB_Codigo,5,1)='0') 
       then Right(AVAB_Codigo,6) 
       else (SUBSTRING(AVAB_Codigo,5,1) & Right(AVAB_Codigo,6)) 
      end as [UL/UE]
    -- 2nd attempt ----------------------------------------------------------------------
      case when (SUBSTRING(cast(AVAB_Codigo as varchar(10)),5,1)='0') 
       then Right(cast(AVAB_Codigo as varchar(10)),6) 
       else (SUBSTRING(cast(AVAB_Codigo as varchar(10)),5,1) & Right(cast(AVAB_Codigo as varchar(10)),6)) 
      end as [UL/UE],

    The concatenation operation is the plus sign, not the ampersand. 

  • Cast string to char

    Hello;
    Could anyone tell me how to cast a string to char?
    for example;
    String [] args = {"test", "hello","a"};
    how can I cast the args[2] to char = 'a';
    Thanks

    Hello;
    Could anyone tell me how to cast a string to char?
    for example;
    String [] args = {"test", "hello","a"};
    how can I cast the args[2] to char = 'a';
    Thanks
    If you want to cast a String to a char you cannot. There are some conditions for casting. You just cannot cast anything primitive or object type to anything. how ever if you want to convert a String to a char array you could d othat as follows
    refer to String API
    public char[] toCharArray()
    Converts this string to a new character array.

  • Exception while casting int[] to Object[],why?

    if(params.getClass().isArray()) this.params = (Object[])params;
    else this.params = new Object[]{params};
    Now I transfer int[] as "params",and ClassCastException is thrown while casting params to Object[].Since I'm using JDK5.0,why does this happen(the array has been initialized)?

    But how to retrieve every element of this
    Object(Array)? Which type should you cast it to?int[] obviously. Or forget about casting and simply create an Integer[] yourself. a for loop isn't that difficult to write.
    Are you aware that arrays are objects? That's why java doesn't autobox an int[].
    By the way, you should look at these lines of code again:
    if(params.getClass().isArray())
    this.params = (Object[])params;
    else this.params = new Object[]{params};

  • Converting int to char

    Hi!..
    I have a problem!...
    I need to convert integers to chars, but i`m using char(int)....
    So, only accept until ascii code 128..
    Please, What can I do?
    This is my code:
    Thanks!
    public Convert() {
    public static void main(String[] args) {
    Convert convert1 = new Convert();
    System.out.print(f_Transforma("ABCD"));
    public static String f_Transforma(String Password)
    int IntStrLong=Password.length();
    String StrResultado=new String();
    while (IntStrLong >=1)
    int tmpchar=(int)Password.charAt(IntStrLong-1); //valor ascii
    tmpchar=256-tmpchar+IntStrLong;
    String aChar = new Character((char)tmpchar).toString(); //ASCII code to String
    StrResultado=StrResultado+aChar;
    IntStrLong-=1;
    return (StrResultado);
    }

    I did what you told me and nothing happened...
    int tmpchar=(int)Password.charAt(IntStrLong-1); //valor ascii
    tmpchar=256-tmpchar+IntStrLong;
    tmpchar=tmpchar>>8;
    String aChar = new Character((char)tmpchar).toString(); //ASCII code to String

Maybe you are looking for

  • How to configure sub-groups in the UME (Group Path) using AD/LDAP

    I trying to find examples and/or documentation on how to bring all the sub groups within a OU.  I could also use a definition of what a 'sub-group' is.  We are trying to configure a datasource as Microsoft AD read-only & database.  I have been able t

  • Keynote remote sincying issues

    Just updated Iphone4 and Ipad 2 and can no longer sync via blue tooth keynote/keynote remote any advice?

  • Internal Error 2318

    Hi All, I hope I can find an answer for the problem I have with updating/installing Java 7 (JRE) update 67 32 bit on Windows 8.1 x64 bit system. The 64 bit Java 7 update 67 installs fine. In the past there were no issues with updating JRE 32 bit to n

  • MBP missing first letter still missing after firmware upgrade

    hahahaha I have been waiting for... this? I still miss as many first letters intermittently, particularly on the first word in a field or after a delay... Great, just great. I can't wait to re-sell this MBP like I do every year, to pay half of the co

  • Communication protocol applet and server application

    Hello, I want to read and write on server port such that applet is communicating with a server application. Can any body suggest me any application level communication protocol or algo so that read and write are syncronised. There is no blocking b/w