1

I'm trying to save string in to a character array using the below code & im getting this error: Type mismatch: cannot convert from char to char[]

Below is the code

public class ExCaluculator{
char[] swi=new char[10];
String San="hello world" ;
int samsu ;
public void excal(){

for(samsu=0;samsu>San.length();samsu++)
{
    swi=San.charAt(samsu);
}   
}
}

Also please suggest me any other methods to do the same

2
  • What is unclear? You can not assign a charto and char[]! Commented Feb 25, 2015 at 7:28
  • 1
    You need to access the array with an index, like swi[samsu] or just use String.toCharArray(). Commented Feb 25, 2015 at 7:30

3 Answers 3

1

ou have to assign the value to an element of the array:

public class ExCaluculator{
char[] swi=new char[10];
String San="hello world" ;
int samsu ;
public void excal(){

for(samsu=0;samsu>2;samsu++)
{
    swi[samsu]=San.charAt(samsu);
}   
}
}
Sign up to request clarification or add additional context in comments.

2 Comments

There is not reason to do this by hand. As @Kayaman said String.toCharArray() should be the prefered way.
@SubOptimal there's a very good reason to do it by hand if you don't yet understand arrays and indexing and are trying to figure it out, as OP clearly is.
0

Array must be accessed with an index and you need a change in condition of for statement.

for(samsu=0;samsu<San.length();samsu++)
{
    swi[samsu]=San.charAt(samsu);
}   

Also you have to increase the array size to 11 (char[] swi = new char[11];) in order to avoid ArrayIndexOutOfBoundsException.

Or Simply you can use

char[] xyz = san.toCharArray();

Refer: Arrays

Comments

0

You can't assign a char to char[], array is subscript based. use something like

swi[0] = San.charAt(samsu);

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.