简体   繁体   中英

using charAt() function assigning to the char array is throwing error

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

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);
}   
}
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM