-1

I just wrote a program for searching an element in an array. It worked fine though. BUT, when I changed the access specifier of variable int i to public, error comes (it had no explicit access modifier before, so I thought access was default). So what am I doing wrong? Thanks.

public class Search {
    public static void main(String args[]) {
        int arr[] = new int[5];
        public int i;
        int num, flag = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the array elements");
        for (i = 0; i < arr.length; i++)
            arr[i] = sc.nextInt();
        System.out.println("Enter the number to be found");
        num = sc.nextInt();
        for (i = 0; i < arr.length; i++) {
            if (num == arr[i]) {
                System.out.println("Element Found!");
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            System.out.println("Element not found");
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • public class Search { public static void main(String args[]) { int arr[] = new int[5]; public int i; int num, flag = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter the array elements"); for(i=0; i – asfas asf May 14 '17 at 07:33
  • 2
    No. You can't declare a class field **inside** a method. – Elliott Frisch May 14 '17 at 07:35
  • What do you mean Elliott? I'm new into Java. Thanks for understanding an d replyin. – asfas asf May 14 '17 at 07:35
  • What do you mean you changed access specifier of variable to int? Int isn't an access specifier, it's a type. – TZHX May 14 '17 at 07:36
  • @TZHX Read the title. – Elliott Frisch May 14 '17 at 07:36
  • @asfasasf I mean exactly what I said. You **can't** have `public int i;` *in* `main` (or any other method). – Elliott Frisch May 14 '17 at 07:37
  • @ElliottFrisch I did read the title, then I read the question. Using the right words to describe problems is important in programming. – TZHX May 14 '17 at 07:38
  • 1
    Oh, so with any variable or method, I cannot use access specifier in main method? To do that, I must declare/initialize it as a class member, right? – asfas asf May 14 '17 at 07:39
  • Possible duplicate of [Why access specifiers can't be used for variables declared inside method in a Java Class?](http://stackoverflow.com/questions/11832001/why-access-specifiers-cant-be-used-for-variables-declared-inside-method-in-a-ja) – Ole V.V. May 14 '17 at 08:22

1 Answers1

1

You cannot use Access Modifier, such as private and public inside a method.

You can have int i = 0;inside a method.

Sky
  • 1,435
  • 1
  • 15
  • 24