【问题标题】:How to add the content in an array together for one output? [closed]如何将数组中的内容添加到一个输出中? [关闭]
【发布时间】:2014-09-14 22:49:06
【问题描述】:

几乎我必须添加用户从数组输入的数字。所以这就是我所拥有的。

Scanner input=new Scanner(System.in);

int[] array1=new int[5];
System.out.print("Enter the first number.");
array1[0]=input.nextInt();
System.out.print("Enter the second number.");
array1[1]=input.nextInt();
System.out.print("Enter the third number.");
array1[2]=input.nextInt();
System.out.print("Enter the fourth number.");
array1[3]=input.nextInt();
System.out.print("Enter the fifth number.");
array1[4]=input.nextInt();



System.out.println("The grand sum of the numbers you entered is :"+(array1));

【问题讨论】:

  • 如果您使用的是 java8,这里是快速解决方案。 stackoverflow.com/questions/4550662/…
  • 对于结构上的任何求和都认为“循环”:)
  • @Robert 我发布了我的答案,并解释了很多。让我知道你是怎么过的:)

标签: java arrays eclipse addition


【解决方案1】:
int sum = 0;
for(int i: array1)
    sum += i;
System.out.println("The grand sum of the numbers you entered is :" + sum);

【讨论】:

    【解决方案2】:

    首先从数组的定义开始

    1. 数组是一个容器对象,它包含固定数量的单一类型值。
    2. 数组的长度是在创建数组时确定的。
    3. 创建后,它的长度是固定的。

    示例

    那么让我们看看你需要处理什么来做你的添加?

    循环

    循环的定义:

    如果您需要多次执行某个代码块或迭代一系列值,则使用循环。

    Java 中有 3 种不同的循环方式

     Name                      Synatx
    

    1。 for loopfor(initialization; Boolean_expression; update){ //Statements}

    1. while loopwhile(Boolean_expression){//Statements}

    2. do while loopdo{//Statements }while(Boolean_expression);

    根据Java中循环的定义,这里需要使用循环,因为要进行加法 根据需要多次

    让我们用 while 循环解决您的问题

    你需要一个累加器变量,比如

    int sume = 0;
    

    遵循for循环的语法

    for(initialization; Boolean_expression; update)
    {
       //Statements
    }
    

    所以你的整个代码变成了:

     int sum = 0;
     for(int i=0; i< array1.length; i++){
          sum = sum + array1[i]
       }
    

    你将从索引零开始并继续添加直到索引将小于数组的长度为什么因为数组索引在 java 中从零开始。 在 for 循环中,您将每个元素的内容添加到累加器中,以得出您正在寻找的总和。

    【讨论】:

    • 干得好,但这个答案可能有点……“过度设计”。小错字:你所说的while 循环实际上是for 循环。最后,我认为 for-each 循环在这种情况下是最合适的。我们应该尽可能避免进行手动索引运算。
    【解决方案3】:

    我不得不使用array1[0]+array1[1]+array1[2]+array1[3]+array1[4]

    【讨论】:

    • 你最好使用@isomarcte的方法。
    • @5gon12eder 我完全不同意 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多