+ 2
Why it gives an error??
import java.util.Arrays; import java.util.Scanner; class Main{ int[]arr=new nextint[3]; public static void main(String args[]){ for(int i=0;i<3;i++){ arr[i]=i; } System.out.println(arr[1]); } System.out.println(arr[1]); }
9 Respuestas
+ 4
Shruti Shukla
1 - Because you cannot directly print inside Class, you need method.
2 - initialisation of array is wrong, there should be int instead of nextint. nextInt is a method of scanner class.
3 - You can't call any non-static things inside static method so make arr static
So here is your solution with explanation:
https://code.sololearn.com/cpxKfSJOuzD1/?ref=app
+ 2
Martin Taylor ,i am not learning java from this app
+ 2
The problem is that the "println" method is static, so it can only be called in a static context like the "main" method.
+ 1
import java.util.Arrays;
import java.util.Scanner;
class Main{
int[]arr=new nextint[3];
public static void main(String args[]){
for(int i=0;i<3;i++){
arr[i]=i;
}
System.out.println(arr[1]);
}
System.out.println(arr[1]);
}
+ 1
Aj-soloHelper ,in your code what do you means by this line -Main m=new Main()?
+ 1
Shruti Shukla
Creating object of Main class. Whenever you create an object of the class, constructor will automatically invoke and printed value inside constructor will be print on terminal.
+ 1
Shruti Shukla this ( Main m = new Main(); ) this is called object creation may be you are new in java . But when you creating any class and you compiling it by default constructor calling at a time of object .
Constructor name is always same as class name here class name is Main so constructor is also with same same Main() this is non parameterized constructor .
And the purpose is to initialize the object.
Once try to make simple class program and create one object and run your file via command line.
Then type javap your java file name and press enter you can see default constructor.