簡體   English   中英

如何比較兩個不同大小的數組?

[英]How to compare two arrays of different sizes?

因此,我的任務是逐行讀取文件並將整數存儲到數組中。 然后將整數添加到點1-5、2-6、3-7等中,並將其存儲到新數組中。

在數組1中,比數組2多4個值。我需要比較這些數組,看看array1是否比array2大0.999。

如果確實更大,則需要打印出數組1中數字的位置。

現在我的問題是我的代碼輸出的是每個數字都大於數組2中的相應數字。

碼:

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class Asgn7
{
    public static void main(String[] args) throws FileNotFoundException
    {   
        Scanner file = new Scanner(new File("asgn7data.txt"));
        double[] array = new double[file.nextInt()];
        double[] newArray = new double[array.length - 4];
        double tempVal = 0;
        int j = 0;
        int count = 0;

        while(file.hasNext())
        {
        for(int i = 0; i < array.length ; i++)
        {
            array[i] = file.nextInt();
        }

        for(j = 0; j < array.length - 4; j++)
        {
            for(int k = 0; k < 5; k++)
            {
                newArray[j] += array[j+k] / 5;  
             }

        }

        for(int i = 2; i < array.length; i++)
        {
            if(array[i] > (newArray[i-2] + 0.999));
            {
                count++;
                tempVal = count;
            }

             System.out.println(tempVal);
        }   
        }

    }
}

在此處輸入圖片說明

應該比較的值是從3-13。

從圖片來看,您沒有將值放置在第二個數組中的正確索引中,或者沒有匹配正確的值。

如果您希望它看起來與圖片完全相同,則應聲明第二個數組:

double[] newArray = new double[array.length - 2];

並且填充它的循環應更改為:

    for(j = 2; j < array.length - 2; j++)
    {
        for(int k = -2; k <= 2; k++)
        {
            newArray[j] += array[j+k] / 5;  
        }

    }

這會將平均值放在newArray的第三,第四,第五...元素中。 現在,您可以直接比較它們:

    for(int i = 2; i < array.length - 2; i++)
    {
        if(array[i] > (newArray[i] + 0.999))
        {
            count++;
            tempVal = count;
        }

        System.out.println(tempVal);
    }

如果要像原來一樣保存兩個未使用的空間,而不是完全響應圖片,則應像最初那樣計算值。 但是請記住將每個元素與元素之前的兩個位置進行比較, 並在結束前的2個位置停止

代替

for(int i = 2; i < array.length; i++)

采用

for(int i = 2; i < array.length - 2; i++)

要打印位置,不需要帶有counttempVal構造。 您只需要打印i+1 另請注意,您有一個; 之后您if 這意味着if為空,並且始終執行之后的塊。 從來沒有一個; ifforwhile等之后。

只是看一下代碼就不清楚您要問的是什么,但不懷疑邏輯是什么:

  for(int i = 2; i < array.length; i++) { if(array[i] > (newArray[i-2] + 0.999)); { count++; tempVal = count; } System.out.println(tempVal); } } 

如果您按以下方式重新放置system.out行,我認為您將獲得如下期望的結果:

    for(int i = 2; i < array.length - 2; i++)
    {
        if(array[i] > (newArray[i-2] + 0.999));
        {
            System.out.println(tempVal);
            // count++;
            // tempVal = count;
        }


    }   
    }

PS:請注意,我還更改了循環的邊界,以在數組的第13個成員而不是第15個成員上停止迭代。

您確定要正確解析數字嗎? 請參見Java:將文件中的整數讀入數組中為什么在解析以進行驗證后不打印出來?

順便說一句,這將使第二個數組的索引溢出(因為它是使用新的double [array.length-4]創建的):

for(int i = 2; i < array.length; i++)

那么您的代碼會運行嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM