How can i pass an array to an object during its intialisation in java? this gives me an error num cant be resolved (last line of code) -
as new java...i want know why following code throws error num cant resolved although have declared array , intialised it. trying pass array object during creation of object.... not allowed or there other error in code?
import java.util.scanner; public class search { public search(int x[]) { (int i=0;i<10;i++) system.out.println("inside constructer"+x[i]); } public static void main(string[] args) { integer num[] = new integer[10]; scanner sc =new scanner(system.in); system.out.println("eneter 10 integers:"); for(int i=0;i<10;i++) { system.out.println("enter "+(i+1)+" number:"); num[i]=sc.nextint(); } for(int j=0;j<10;j++) system.out.println(num[j]); } search obj=new search(num); }
integer , int 2 different things. change
integer num[] = new integer[10];
int num[] = new int[10];
int primitive type while integer object wraps int primitive type.
also in constructor don't hard code 10 in loop x.length instead.
public static void main(string[] args) { int num[] = new int[10]; scanner sc = new scanner(system.in); system.out.println("eneter 10 integers:"); (int = 0; < 10; i++) { system.out.println("enter " + (i + 1) + " number:"); num[i] = sc.nextint(); } (int j = 0; j < 10; j++) { system.out.println(num[j]); } search obj = new search(num); } public class search { public search(int x[]) { (int = 0; < 10; i++) system.out.println("inside constructer" + x[i]); } }
Comments
Post a Comment