猿问

针对特定数据集验证 ArrayList 内容

我想检查并验证 ArrayList 中的所有内容是否与 String 变量的值相似。如果任何值不相似,则打印索引号并显示错误消息(索引 2 处的值与 expectedName 变量的值不匹配)。在我运行下面的代码后,它会打印所有三个索引和错误消息,它不会只打印索引号 1。请注意,这里我从 CSV 文件中获取数据,将其放入数组列表中,然后进行验证它针对 String 变量中的预期数据。


import org.apache.commons.csv.CSVFormat;

import org.apache.commons.csv.CSVParser;

import org.apache.commons.csv.CSVRecord;

import java.io.IOException;

import java.io.Reader;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.ArrayList;


public class ValidateVideoDuration {

private static final String CSV_FILE_PATH = "C:\\Users\\videologs.csv";

public static void main(String[] args) throws IOException {


    String expectedVideo1Duration = "00:00:30";

    String expectedVideo2Duration = "00:00:10";

    String expectedVideo3Duration = "00:00:16";


    String actualVideo1Duration = "";

    String actualVideo2Duration = "";

    String actualVideo3Duration = "";


    ArrayList<String> actualVideo1DurationList = new ArrayList<String>();

    ArrayList<String> actualVideo2DurationList = new ArrayList<String>();

    ArrayList<String> actualVideo3DurationList = new ArrayList<String>();


    try (Reader reader = Files.newBufferedReader(Paths.get(CSV_FILE_PATH));

            CSVParser csvParser = new CSVParser(reader,

                    CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());) {

        for (CSVRecord csvRecord : csvParser) {

            // Accessing values by Header names

            actualVideo1Duration = csvRecord.get("Video 1 Duration");

            actualVideo1DurationList.add(actualVideo1Duration);

            actualVideo2Duration = csvRecord.get("Video 2 Duration");

            actualVideo2DurationList.add(actualVideo2Duration);

            actualVideo3Duration = csvRecord.get("Video 3 Duration");

            actualVideo3DurationList.add(actualVideo3Duration);


        }

    }


九州编程
浏览 91回答 1
1回答

紫衣仙女

不要使用==或!=进行字符串比较。==检查两个字符串的引用相等性而不是值的相等性。请改用该.equals()方法。将您的 if 条件更改为if (!actualVideo2DurationList.get(i).equals(expectedVideo2Duration))
随时随地看视频慕课网APP

相关分类

Java
我要回答