首页 > 解决方案 > 如何编写返回二维数组指定列中所有元素之和的程序

问题描述

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

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

首先要求用户输入一个 3 x 4 数组。用户应输入如下数组: 2.6 5.1 6 8 5.4 4.4 7 1 9.5 7.9 2 3

然后程序应该计算数组中每一列的总和。

 

尝试强制转换为 double 或 ints 无效

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");
        }
    }
}

标签: javaarrays

解决方案


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);
    }
}

推荐阅读