I am trying to store a string into an integer array with the following code:
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Integer.parseInt( s.charAt(i));
}
}
eclipse is giving me an error saying: the method parseInt(string) is not applicable for the arguments (char)
What am I doing wrong?
6 Answers 6
You need to parse the char
, or convert it to a String
.
If you're trying to get one digit at a time, and you know your input is a digit, then the easiest way to convert a single digit to an int
is just
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
If you want to keep using Integer.parseInt
, then just do
intArray[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
// or
intArray[i] = Integer.parseInt(s.substring(i, i+1));
-
thanks, This makes sense but I am still getting an error probably because of something else I am doing wrong..Sackling– Sackling2012年03月22日 17:09:49 +00:00Commented Mar 22, 2012 at 17:09
That's because Integer.parseInt()
expects a String
as parameter, while you are passing a char
(s.charAt()
returns a char
).
Since you are creating the array one digit at a time, a better way to get the decimal representation would be:
intArray[i] = s.charAt(i) - '0';
char is not a String so use a substring function s.substring(i, i+1)
or better intArray[i] = s.charAt(i)
s.charAt
returns a char.
+ parseInt
take a String
= Eclipse gives you the compilation error
You may create a String from the char if really needed:
s.charAt(i)+""
String[] split = s.split("");
int[] nums = new int[split.length];
for(int i = 0; i < split.length; i++){
nums[i] = Integer.parseInt(split[i]);
}
public class Storing_String_to_IntegerArray
{
public static void main(String[] args)
{
System.out.println(" Q.37 Can you store string in array of integers. Try it.");
String str="I am Akash";
int arr[]=new int[str.length()];
char chArr[]=str.toCharArray();
char ch;
for(int i=0;i<str.length();i++)
{
arr[i]=chArr[i];
}
System.out.println("\nI have stored it in array by using ASCII value");
for(int i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println("\nI have stored it in array by using ASCII value to original content");
for(int i=0;i<arr.length;i++)
{
ch=(char)arr[i];
System.out.print(" "+ch);
}
}
}