1

I am using JAVA for coding. My Aim is to put Location of array into that position of array and it has to be a char array My current Code:-

    char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]=i+1+'0';
    }

or

    char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]=i+1;
    }

Is not working for java and am getting error "Cannot convert int to char". I have tried finding out about it but i only received solution for c++ and that code dosent work in Java giving the same error.

1
  • Thank You everyone, arr[i] = (char)(i + 1); works Commented Mar 22, 2017 at 19:51

3 Answers 3

1

You just need to cast the value you are trying to put into the array as a char. The reason for this is that char is a 16 bit number and int is 32 bits

   char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]=(char) (i+1+'0');
    }

or

    char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]= (char)(i+1);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Try to cast it explicitly to a char.

arr[i] = (char)i + 1;

or maybe

arr[i] = (char)((char)i + 1);

If the output of char + char gives an int (because of whatever reason you can think of).

Comments

0

Because you are trying to assign an integer value to a char! Cast it to char first.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.