【问题标题】:Java - How to add the first value of an array with the last one and so onJava - 如何将数组的第一个值与最后一个值相加,依此类推
【发布时间】:2015-02-22 21:10:48
【问题描述】:

我需要将数组的位置 0 中的值与最后一个位置相加,位置 1 中的值与倒数第二个等等...

示例:

1:8

2:6

3:4

4:2

5:1

6:7

7:3

结果: 11、13、5、2

数组的大小由用户在运行程序时声明,值也是如此。

package act4p1;
import java.io.*;
public class Act4p1 {

public static BufferedReader entrada = new BufferedReader (new InputStreamReader(System.in));
    public static void main(String[] args) throws IOException {
        int tam;

        System.out.println("Cantidad de los elementos del arreglo: ");
        tam = Integer.parseInt(entrada.readLine());
        int[] arreglo = new int [tam];

        System.out.println("Teclea los "+tam+" valores");

        for (int i = 0; i < arreglo.length; i++) {
             System.out.print(i+": ");
             arreglo[i] = Integer.parseInt(entrada.readLine());
        }

        //Code needed here

        System.out.print("\nElementos del arreglo: ");
        for (int x = 0; x < arreglo.length; x++) {
            System.out.print(arreglo[x] + ", ");
        }


    }

}

【问题讨论】:

  • 你有没有代码,没有电脑你会怎么做?
  • Stack Overflow 不是为了让别人为你写代码。
  • 我投票结束这个问题,因为它是代码编写请求。
  • //Code needed here 是 100% 正确的,我们仍然需要查看您的代码编写尝试,应该放在那里。请记住,根据stackoverflow.com/help/on-topic 3. 要求家庭作业帮助的问题必须包括您迄今为止为解决问题所做的工作的总结,以及您遇到的困难的描述已经解决了.

标签: java arrays logic


【解决方案1】:

好吧,你可以使用这样的函数:

public int[] sumFirstLastArray(int[] input)
{
    int inputSize=input.length; // length gives the array size
    int outputSize=(input.length+1)/2; //to get 1 more space if input is odd
    int[] output= new int[outputSize]; // initializes the result array

    for(int i=0;i<inputSize/2;i++)
    {
        output[i]=input[i]+input[inputSize-i-1];
        // inputSize-i-1 gives the ith last position of the array.
        // the -1 is necessary due to the array being from 0 to inputSize-1
    }

    if(inputSize%2==1) //check for odd input arrays
    {
        output[inputSize/2]=input[inputSize/2];
        //copy the middle element
    }

    return output;
}

cmets 解释了这个函数背后的逻辑。至于获取输入,这取决于您用于获取输入的内容。

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    相关资源
    最近更新 更多