我刚刚在eclispe中练习java程序,代码如下:
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 a 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 is "+sum);
}
}
=============================================== =========================== 上面的代码运行正常,没有任何错误。但是,如果我想使用另一个类作为&#34;类sum_of_digits&#34;使用以下代码。它开始在课程中显示错误&#34; sum_of_digits&#34;我甚至在创建对象之前。以下是代码:
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 is "+sum);
}
=============================================== ======================= 但是,如果我在方法中包含for循环并进行必要的安排,那么代码工作正常,它运行没有错误,我得到了所需的结果:下面是带有类&#34; sum_of_digits&#34;的新代码:< / p>
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 is "+sum);
}
}
class Problem7
{
public static void main(String args[])
{
sum_of_digits digit = new sum_of_digits();
System.out.println("Enter a 5 digit number");
try(Scanner n1 = new Scanner(System.in))
{
digit.num = n1.nextInt();
}
digit.loop();
}
}
我的问题是为什么我不能直接在课堂上声明for循环&#34; sum_of_digits&#34;?
答案 0 :(得分:3)
你在课堂上有一个for循环。这里不允许这样做。
class sum_of_digits
{
int num, sum=0, mod_num, count;
for(count = 0; count <= 4; count=count+1)
{
}
}
像这样的可执行语句需要在方法,构造函数或初始化程序块中。
class sum_of_digits
{
int num, sum=0, mod_num, count;
void loop() {
for(count = 0; count <= 4; count=count+1)
{
}
}
}