声明变量和赋值

Declaring variable and assignment

刚才在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);
}
}

============================================= ============================= 上面的代码运行正确,没有任何错误。但是,如果我想使用与以下代码不同的 class 作为 "class sum_of_digits"。在我什至创建 object.Following 之前,它就开始在 class "sum_of_digits" 中显示错误 object.Following 是代码:

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 循环并进行必要的安排,那么代码工作正常,它运行时没有错误,我得到了想要的结果: 下面是带有 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 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();
}
}

我的问题是为什么我不能直接在 class "sum_of_digits" 中声明 for 循环?

您在 class 正文中有一个 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)
        {

        }
    }
}