Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can anyone help me to fix this little problem

 
vuthlarhi donald
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Main {

/** Creates a new instance of Main */
public Main(int...num) {
int i;
int sum = 0;
for(i=0;i<num.length;i++)
{
sum += num[i];
}
System.out.println(num);
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Main mt = new Main (12,14,14);

}

}
 
Sergey Petunin
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a mere typo. In the constructor, after the calculation is finished, you're printing "num" instead of "sum".
 
Deepak Sagar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per statement "Main mt = new Main (12,14,14);" you are passing three int values. But in constructor, argument is considered as array.

In order to send the initialized array, can declare the int array variable and pass that array while creating the instance.



public class Main {

/** Creates a new instance of Main */
public Main(int[] num) {
int i;
int sum = 0;
for(i=0;i<num.length;i++)
{
sum += num[i];
}
System.out.println(sum);
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int []arr={12,13,14}; //Array Intialization
Main mt = new Main (arr);

}

}

Please correct me if I am wrong
 
Sergey Petunin
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You really can pass an initialized array as a var-arg parameter, that's true. But you also can pass several values, as in vuthlarhi donald 's code, nothing's wrong here. Actually, that's the point of var-arg.
[ December 18, 2007: Message edited by: Serge Petunin ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic