打印数组中5个元素的总和

时间:2021-11-14 12:02:57

well when i am trying to run this code below in java it is telling out of bounds but the program is logically correct:

好吧,当我试图在java中运行以下代码时,它告诉了界限,但程序在逻辑上是正确的:

import java.io.*;
class array2
{
    public static void main(String args[]) {
        Scanner sc=new Scanner(System.in);
        int a[]=new int[5];
        int i,sum=0;

        for(i=1;i<=5;i++) { 
            System.out.println("enter the numbers");
            a[i]=sc.nextInt();
        }

        for(i=1;i<=5;i++) {
            sum=sum+a[i];
        }

        System.out.println(+sum);
    }
}

3 个解决方案

#1


1  

Change

for(i = 1; i <= 5; i++)
...
System.out.println(+sum);

to

for(i = 0; i < 5; i++)
...
System.out.println(sum);

So as to start from the first element, 0 indexed.

从第一个元素开始,0索引。

#2


1  

Your creating an array, this means its position starts at 0 you are starting at 1 and trying to run for 5 times. try starting at 0:

你创建一个数组,这意味着它的位置从0开始,你从1开始并尝试运行5次。尝试从0开始:

import java.io.*;
    class array2
    {
    public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    int a[]=new int[5];
    int i,sum=0;
    for(i = 0; i < 5; i++)
    { 
    System.out.println("enter the numbers");
    a[i]=sc.nextInt();
    }
    for(i = 0; i < 5; i++)
    {
    sum=sum+a[i];
    }
    System.out.println(+sum);
    }
    }

#3


1  

Arrays start at 0 and end at length - 1 but you don't need any array here. You can do

数组从0开始并以长度结束 - 1但这里不需要任何数组。你可以做

Scanner sc=new Scanner(System.in);
long sum = IntStream.range(0, 5)
                    .map(i -> {
                         System.out.println("enter the numbers");
                         return sc.nextInt();
                     })
                    .sum();
System.out.println("sum: " + sum);

#1


1  

Change

for(i = 1; i <= 5; i++)
...
System.out.println(+sum);

to

for(i = 0; i < 5; i++)
...
System.out.println(sum);

So as to start from the first element, 0 indexed.

从第一个元素开始,0索引。

#2


1  

Your creating an array, this means its position starts at 0 you are starting at 1 and trying to run for 5 times. try starting at 0:

你创建一个数组,这意味着它的位置从0开始,你从1开始并尝试运行5次。尝试从0开始:

import java.io.*;
    class array2
    {
    public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    int a[]=new int[5];
    int i,sum=0;
    for(i = 0; i < 5; i++)
    { 
    System.out.println("enter the numbers");
    a[i]=sc.nextInt();
    }
    for(i = 0; i < 5; i++)
    {
    sum=sum+a[i];
    }
    System.out.println(+sum);
    }
    }

#3


1  

Arrays start at 0 and end at length - 1 but you don't need any array here. You can do

数组从0开始并以长度结束 - 1但这里不需要任何数组。你可以做

Scanner sc=new Scanner(System.in);
long sum = IntStream.range(0, 5)
                    .map(i -> {
                         System.out.println("enter the numbers");
                         return sc.nextInt();
                     })
                    .sum();
System.out.println("sum: " + sum);