Sackling
Sackling

Reputation: 1820

storing string in an integer array.

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?

Upvotes: 1

Views: 10695

Answers (6)

Akash Dhotre
Akash Dhotre

Reputation: 1

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

}

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198481

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

Upvotes: 6

Mig
Mig

Reputation: 796

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';

Upvotes: 1

user1181445
user1181445

Reputation:

String[] split = s.split("");
int[] nums = new int[split.length];
for(int i = 0; i < split.length; i++){
  nums[i] = Integer.parseInt(split[i]);
}

Upvotes: 0

Michael Laffargue
Michael Laffargue

Reputation: 10314

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)+""

Upvotes: 0

Alexey A.
Alexey A.

Reputation: 1419

char is not a String so use a substring function s.substring(i, i+1) or better intArray[i] = s.charAt(i)

Upvotes: 0

Related Questions