-1
public static void main(String[] args) {            
        int no;
        String s;
        s = "12345";
}

I want to convert the string s to an integer named no.
How can I do that?

Idos
  • 15,053
  • 14
  • 60
  • 75
Shubham
  • 13
  • 4

3 Answers3

0

This is very easy, to get your String as an integer use:

no = Integer.parseInt(s);

And if you wish to convert it to a char array use:

char[] charArray = ("" + no).toCharArray();

Then if you wish to get an int from a specific char you can use:

int x = Character.getNumericValue(charArray.charAt(0)); // or any index instead of 0
Idos
  • 15,053
  • 14
  • 60
  • 75
0

You need to be sure the string is parsable to integer if so, try this:

for (int i = 0; i < items.length; i++) {
    try {
        results[i] = Integer.parseInt(items[i]);
    } catch (NumberFormatException nfe) {};
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Make use of the parseInt() function available in Java. Your program will be-- You wanted an individual character seperately. For that the program will go something like this--

public class test{
public static void main(String args[]){

    String s = "12345";
    char[] charArray = s.toCharArray();

    int a[] = new int[charArray.length];

    String[] strarray = new String[charArray.length];

    for(int i=0;i<charArray.length;i++){
        strarray[i] = String.valueOf(charArray[i]);
        a[i] = Integer.parseInt(strarray[i]);
    }

    for(int i=0;i<charArray.length;i++){
        System.out.print(strarray[i]);
    }

    System.out.println();

    for(int i=0;i<charArray.length;i++){
        System.out.print(a[i]);
    }

}

}

Here we are storing the individual values of String into a character variable of type array. Define the length of the string array same as that of the length of the character array(Cause you have that many elements.). Store the values present in each character array into the string array. At the same time convert the string to integer using parseInt() and store it in an integer array. That's it!