如何编写一个程序以返回二维数组指定列中所有元素的和

时间:2019-04-02 13:40:38

标签: java arrays

任何帮助将不胜感激,主要停留在这个问题上,它根本无法运行,我迷失了方向,标准是:

编写一个程序,该程序返回二维数组指定列中所有元素的和。

首先要求用户输入3乘4的数组。 用户应按以下步骤输入数组: 2.6 5.1 5.1 8 5.4 4.4 4.4 7 1 9.5 7.9 2 2 3

程序应随后计算数组中每个列的总和。

尝试将类型转换为双精度或整数无用

package com.company;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        double[] Array1 = new double[5];
        double[] Array2 = new double[5];
        boolean Equal = true;

        Scanner input = new Scanner(System.in);
        System.out.print("Please enter " + Array1.length + " values");
        for (int i = 0; i < Array1.length; i++) {
            Array1[i] = input.nextDouble();
        }
        Scanner input2 = new Scanner(System.in);
        System.out.print("Please enter " + Array2.length + " values for your second array:");
        for (int i = 0; i < Array2.length; i++)
            Array2[i] = input.nextDouble();



        if(Array1.length == Array2.length)
        {
            for (int i = 0; i < Array1.length; i++)
            {
                if(Array1[i] != Array2[i])
                {
                    Equal = false;
                }
            }
        }
        else
        {
            Equal = false;
        }

        if (Equal)
        {
            System.out.println("Two Arrays Are Equal");
        }
        else
        {
            System.out.println("Two Arrays Are Not equal");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public class Main{

    static double[][] mat;

    public static void main(String[] args){
           Scanner input=new Scanner(System.in);
           System.out.println("Enter number of rows and number of columns");

           int n=input.nextInt();
           int m=input.nextInt();
           mat=new double[n][m];
           System.out.println("Please enter elements of matrix");

           for(int i=0;i<n;i++){
               for(int i=0;i<m;i++){
                   mat[i][j]=input.nextDouble();
               }
           }

          System.out.println("Enter column number to get sum");
          double sum=0D;
          int col=input.nextInt();
          for(int i=0;i<m;i++){
              sum+=mat[i][col];
          }

         System.out.println("sum of elements of "+col+"in the mat is "+sum);
    }
}