Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal modifier for parameter [variable]; only final is permitted [closed]

Tags:

java

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
like image 882
iShaalan Avatar asked Sep 13 '13 19:09

iShaalan


2 Answers

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; 
    }
}
like image 194
Cruncher Avatar answered Oct 19 '22 22:10

Cruncher


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.

like image 25
Óscar López Avatar answered Oct 20 '22 00:10

Óscar López