Java 数学方程式计划 公共类问题1{ 公共静态void main(字符串参数[]) { int[]a=新的int[1000]; 对于(int counter=0;counter

Java 数学方程式计划 公共类问题1{ 公共静态void main(字符串参数[]) { int[]a=新的int[1000]; 对于(int counter=0;counter,java,Java,,您的代码有两个主要问题: 在for循环的末尾有一个分号 public class problem1 { public static void main(String args []) { int [] a = new int [1000]; for (int counter = 0; counter<=a.length;counter++); { if ((counter % 3 == 0) || (counter % 5 =

,您的代码有两个主要问题:

  • 在for循环的末尾有一个分号

    public class problem1 {
        public static void main(String args [])
        {
        int [] a = new int [1000];
    
        for (int counter = 0; counter<=a.length;counter++);
        { 
            if ((counter % 3 == 0) || (counter % 5 == 0))
            {
                int temp += counter;
            }
        }
    
    }
    }
    
    for (int counter = 0; counter<=a.length;counter++); // Remove the ;
    
并将变量
temp
声明在
for循环
之外,其默认值为
0

一个小问题是:

  • 您不需要数组
    a
    。而是声明一个
    int
    变量,比如
    total
    ,并使用所需的值(在本例中为
    1000
    ),然后在循环条件下使用它,而不是
    a.length

您的代码将永远不会执行,因为for末尾的分号不会给您带来编译错误,但它意味着一个空语句,因此for正文将永远不会执行,只需删除分号即可。

我认为您应该首先在for循环外部初始化
int temp
。它应该如下:
int temp=0;
然后
temp+=计数器;
应该可以工作。

  • 不要为您的计数器创建数组。这是不必要的,数组通常存储可重用的值,例如名称、城市、年龄等

  • 此外,for循环不以分号结尾

  • 最重要的是:不要在循环中声明一个变量。若你们这样做,你们会一次又一次地创建X倍的变量

公共类问题1{
公共静态void main(字符串[]args){
内部温度=0;

对于(int i=0;i)您需要使用调试器。“a”有什么用?这个问题看起来像是在问我。您不需要数组,而是在循环中不断重新声明temp。
int temp += counter;  // replace it with `temp += counter`.
public class problem1 {


public static void main(String[] args) {

    int temp = 0;

    for (int i = 0; i <= 1000; i++)

    {
        if ((i % 3 == 0) || (i % 5 == 0)) {
            temp += i;

        }
    }
    System.out.println("Result is :" + temp);
}

}