java - 如何编写返回二维数组指定列中所有元素之和的程序
问题描述
任何帮助都将不胜感激,主要是停留在这个问题上,它根本无法运行,我迷失了方向,标准是:
编写一个程序,返回二维数组指定列中所有元素的总和。
首先要求用户输入一个 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");
}
}
}
解决方案
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);
}
}
推荐阅读
- python - 在 Python 中使用 Tesseract-OCR 从图像中获取数字
- c# - System.Text.Json 反序列化错误 System.MemoryExtensions 无法加载 System.Runtime.CompilerServices.Unsafe
- kotlin - 如何将一个数据类的值分配给另一个数据类
- spring-boot - Spring Elastic Search java.lang.UnsupportedOperationException 使用 mongo @DBRef
- python-3.x - 无法使用请求模块发送 OTP
- vba - 在 VBA ACCESS 中将数字序列转换为集合
- python - 函数的第二个参数总是被视为 1 的原因是什么?
- python - 将 CSRF 从烧瓶后端移动到 vue
- sql - 如果 1 个表中的日期在表 2 的日期的 24 小时内,则返回 True
- flutter - Flutter protobufs 处理静态和/或实时 GTFS 数据