运行这段代码时,我得到了ArrayIndexOutOfBoundsException。
public class Evensum {
    public static void main(String[] args) {
        int num = Integer.parseInt(args[0]);
        int even[] = new int[num];
        int sum = 0,j = 0;
        String evennums = "";
        //Insert your code here
         for(j=0; j<=num; j++) {
            if(num%2==0) {
                even[j]=num;
                sum=sum+num;
                args[j]= Integer.toString(num);
            }
            evennums=String.join(",", args);
        }    
        System.out.println(evennums);
        System.out.println(sum);
    }
}发布于 2020-02-20 01:35:39
for (j=0; j<=num; j++)这是错误的。它应该是:
for (j = 0; j < num; j++)为什么?假设num为5。在此行之前,您将even初始化为5。even的索引将为0、1、2、3、4。
现在,使用j<=num,您正在尝试访问索引5,该索引不存在,因此出现了异常。
args[j]= Integer.toString(num);此行将引发另一个异常。我假设您只从命令行传递了一个参数,即args[0]。这意味着args数组的大小为1,您不能向其添加更多元素。
此外,向args数组添加/修改元素也不是一种好的做法。您应该为此创建一个新的数组。
发布于 2020-06-27 06:03:58
通过避免使用Integer.toString和String.join传递参数,请找到简单得多的代码版本。简单的整型Arraylist和添加元素将会起到作用。
package com.umapathy.java.learning.programs;
import java.util.ArrayList;
import java.util.List;
public class EvenSum 
{
    public static void main(String[] args)
{   
    int num = 20; //Initialize the user-defined value for the loop execution
    int sum = 0 ; //Initialize the Sum Value as 0
    List<Integer> evenlist = new ArrayList<Integer>(); //Define an integer 
    Array list
    for (int i=2; i<=num; i++) //Begin the loop from the value of 2 
    {
      if(i%2==0) //Logic to find whether a given number is Even Number or not
      {
      sum = sum + i;  // If the logic returns true, Calculate the Sum Value 
      evenlist.add(i); // Add the Integer to the previous defined Integer 
                       // Arraylist by calling add method
       }        
    }
    System.out.println(evenlist); // Print the Output outside the loops
    System.out.println(sum);
     }
  }生成的输出如下:--
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 110发布于 2020-06-30 03:03:12
package javaApp;
public class EvenSum {
    public static void main(String[] args) {
        int num = 20;
        int even[] = new int[num];
        int sum = 0,j = 0;
        String evennums = "";
        for(j=1; j<=num; j++) {
            if(j%2==0) {
                sum=sum+j;
                evennums=evennums+","+j;
            }
        }
        evennums=evennums.replaceFirst(",","");
        System.out.println(evennums);
        System.out.println(sum);
    }
}https://stackoverflow.com/questions/60306062
复制相似问题