heyy, i'm a student so dont attack me please i just dont understand whats wrong with this code why is it giving me an error when i make the array public? it says illegal start which doesnt make sense
package assignment;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.print("Enter array size! ");
int size= in.nextInt();
public int[] array= new int[size]; // error
for (int i=0;i<size;i )
{
System.out.println("Enter numbers: ");
Scanner input= new Scanner(System.in);
array[i]=input.nextInt();
}
'''
any headsup?
CodePudding user response:
Access Modifiers:
If you move the whole line outside of your main function it will work. Access Modifiers such as: "Public, Private, etc." are only allowed outside of functions/methods.
You could also remove the public tag instead of taking the variable out of the function but that would limit your scope.
Scope:
If you want to learn about scope I'd give this a go:
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-scope
It's in javascript but don't let that scare you away, the concepts are the same and JS is easy.
CodePudding user response:
If you want to use array outside any class or package then declare array globally with public access modifier.
import java.util.*;
public class Main
{
public static int[] array; // declare globally
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.print("Enter array size! ");
int size= in.nextInt();
array = new int[size];
for (int i=0;i<size;i )
{
System.out.println("Enter numbers " (i 1) ": ");
Scanner input= new Scanner(System.in);
array[i]=input.nextInt();
}
}
}
CodePudding user response:
Some modifier type are not allowed in method body: public
, private
, protect