java - Declaring variable and assignment -
i practicing java program in eclispe following code:
import java.util.*; class problem7 { public static void main(string args[]){ int num,sum=0,mod_num,count;//syntax error on token ";", { expected after //this token. ques=why? system.out.println("enter 5 digit number"); try(scanner n1 = new scanner(system.in)) { num = n1.nextint(); } for(count = 0; count <= 4; count=count+1) { mod_num = num%10; num=num/10; sum = sum+mod_num; } system.out.println("the sum off digits "+sum); } }
========================================================================== above code runs correctly without error. if wanted use different class "class sum_of_digits" following code. starts shows error in class "sum_of_digits" before create object.following code:
import java.util.*; class sum_of_digits { int num,sum=0,mod_num,count;//syntax error on token ";", { expected after //this token. ques=why? for(count = 0; count <= 4; count=count+1) { mod_num = this.num%10; this.num=this.num/10; sum = sum+mod_num; } system.out.println("the sum off digits "+sum); }
====================================================================== if include loop in method , make necessary arrangements, code works fine, runs without error , desired result: below new code class "sum_of_digits":
import java.util.*; class sum_of_digits { int num,sum=0,mod_num,count;//syntax error on token ";", { expected after //this token void loop() { for(count = 0; count <= 4; count=count+1) { mod_num = this.num%10; this.num=this.num/10; sum = sum+mod_num; } system.out.println("the sum off digits "+sum); } } class problem7 { public static void main(string args[]) { sum_of_digits digit = new sum_of_digits(); system.out.println("enter 5 digit number"); try(scanner n1 = new scanner(system.in)) { digit.num = n1.nextint(); } digit.loop(); } }
my question why cant declare loop directly in class "sum_of_digits"?
you've got loop in class body. it's not allowed here.
class sum_of_digits { int num, sum=0, mod_num, count; for(count = 0; count <= 4; count=count+1) { } }
executable statements need in method, constructor, or initializer block.
class sum_of_digits { int num, sum=0, mod_num, count; void loop() { for(count = 0; count <= 4; count=count+1) { } } }
Comments
Post a Comment