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

时间:2018-06-20 03:02:32

标签: java arrays arraylist

我正在尝试创建一个程序来获取两个向量的点积。我通过创建一个数组列表(命名距离)来实现。通过在main方法中更改此行,可以使该程序使用硬编码数字运行。

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

2 个答案:

答案 0 :(得分:0)

确保在“ vect_A”之后正确拼写距离。

(添加为答案,因为我还无法评论...)

答案 1 :(得分:0)

我将采取稍微不同的方法,而不是尝试使用单个方法调用读取两个数组,而是将其调用两次以读取用户的数组输入。这样,用户还将知道他为arrayA和arrayB输入的值。 因此,您的向量方法将如下所示:

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