I am trying to write a method that gets a string of numbers "123188"
then returns an int[]
which contains digits.
that what I've got so far :
public int[] stringToDig(String a)
{
char [] ch1 = a.toCharArray();
int [] conv = new int [ch1.length];
for (int i=0 ; i<ch1.length ; i++)
conv[i] = Character.getNumericValue(ch1[i]);
return conv;
}
and I got that
Multiple markers at this line:
- Syntax error on token "(", ; expected
- Syntax error on token ")", ; expected
- Illegal modifier for parameter stringToDig; only final is permitted
You can't put methods inside of other methods in Java.
Structure your program like this:
public class Test
{
public static void main(String[] args)
{
int[] digits = stringToDig("54235");
}
public int[] stringToDig(String a)
{
char [] ch1 = a.toCharArray();
int [] conv = new int [ch1.length];
for (int i=0 ; i<ch1.length ; i++)
conv[i] = Character.getNumericValue(ch1[i]);
return conv;
}
}
Try this:
public int[] stringToDig(String a) {
char[] ch1 = a.toCharArray();
int[] conv = new int[ch1.length];
for (int i = 0; i < ch1.length; i++)
conv[i] = Character.digit(ch1[i], 10); // here's the difference
return conv;
}
The preferred method for converting a character digit to the corresponding int
value is by using the digit()
method. Here's another option, although it's a bit of a hack and will only work for digits in base 10 (unlike using digits()
, which works for other bases):
conv[i] = ch1[i] - '0';
Besides that, @Cruncher is right - the errors shown seem to indicate that you forgot to put the method inside a class! follow his advice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With