gpt4 book ai didi

java - 如何将数组列表值返回到单独的数组中?

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:37 24 4
gpt4 key购买 nike

我正在尝试创建一个程序来获取两个 vector 的点积。我通过创建一个数组列表(名为距离)来接近它。我可以通过更改主方法中的这一行来使该程序使用硬编码数字运行。

double vect_A[] = distnace(mag);
double vect_B[] = distance(dista);

我知道上面的代码无法运行,是否可以将这些特定值返回到单独的数组中?或者我是否错误地处理了这个问题。我对 Java 很陌生,任何见解都将不胜感激。

//java implementation for dot product
// and cross product of two vector.
import java.util.Scanner;
import java.util.ArrayList;

class practiceMats {
public static void main (String[] args) {
vector();
double vect_A[] = distnace(mag);
double vect_B[] = distance(dista);

// dotProduct function call
System.out.print ( "Dot product:");
System.out.println (dotProduct(vect_A, vect_B)) ;
}


static double n = 3.0;

// Function that return
// dot product of two vector array.
static double dotProduct(double vectorA[], double vectorB[])
{
double product = 0.0;

// Loop for calculate cot product
for (int i = 0; i < n; i++)
product = product + vectorA[i] * vectorB[i];
return product;
}

static ArrayList<Integer> vector()
{
ArrayList<Integer>distance= new ArrayList<Integer>();
Scanner scan = new Scanner (System.in);
System.out.println("Please enter your array length: ");
int s = Integer.parseInt(scan.nextLine());
System.out.println();

for(int i = 0; i < s; i++) {
System.out.println("Enter your distance: ");
int dista = Integer.parseInt(scan.nextLine());
distance.add(dista);
System.out.println("Enter your distance: ");
int mag = Integer.parseInt(scan.nextLine());
distance.add(mag);
}
return distance;
}
}

最佳答案

我的处理方法略有不同,而不是尝试使用单个方法调用来读取两个数组,我会调用它两次来读取用户的数组输入。这样用户也将知道他为 arrayA 和 arrayB 输入的值。因此你的 vector 方法将如下所示:

     static ArrayList<Integer> vector(int vectorSize) 
{
System.out.println("Kindly provide details for the Vector: ");
ArrayList<Integer>distance= new ArrayList<Integer>();
Scanner scan = new Scanner (System.in);

for(int i = 0; i < vectorSize; i++) {
System.out.println("Enter your distance: ");
int dista = scan.nextInt();
distance.add(dista);
}
return distance;
}

主要方法如下所示:

  public static void main (String[] args) 
{
System.out.println("Please enter your array length: ");
int s = scan.nextInt();
System.out.println();
List<Integer> vectorA= vector(s);
List<Integer> vectorB= vector(s);
double vect_A[] = //convert your List vectorA to array
double vect_B[] = //convert your List vectorB to array

// dotProduct function call
System.out.print ( "Dot product:");
System.out.println (dotProduct(vect_A, vect_B)) ;
}

关于java - 如何将数组列表值返回到单独的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50939567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com