简体   繁体   English

设置字符串值时数组超出界限

[英]Array Out Of Bounds When Setting a String Value

What I want to do is set a String called nameWithYear to be equal to be movies[0] + "(" + movies[1]+")" (So "Movie Title (Year)") from text being parsed off a CSV. 我想做的是设置一个名为nameWithYear的字符串,该字符串等于从CSV解析的文本中的movies [0] +“(” + movie [1] +“)”(因此,“ Movie Title(Year)”) 。

Whenever I try, I am experiencing an issue where I keep on getting an array out of bounds error. 每当尝试时,我都会遇到一个问题,即我不断使数组超出范围错误。 I tried setting the string equal to only movies[0], it works with success. 我尝试将字符串设置为只等于movie [0],它可以成功运行。 When I try to set it to movies[1] by itself, it fails. 当我尝试自行将其设置为movies [1]时,它将失败。 I can do a System.out that includes element [1], and it outputs just fine with no issues. 我可以做一个包含元素[1]的System.out,它输出很好,没有问题。 So in other words, for some reason, I can only include element[0] in the string and not element[1]. 因此,换句话说,由于某种原因,我只能在字符串中包含element [0],而不能包含element [1]。 So I am assuming it has something to do with declaring the value for the string. 因此,我假设它与声明字符串的值有关。 Just not sure what. 只是不确定。
The code is as follows: 代码如下:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CSVParsing { 
public String parseCSV() {

String csvFile = "C:\\Users\\RAY\\Desktop\\movies.csv";
BufferedReader br = null;
String nameWithYear = new String();
    String line = "";
String csvSplitBy = ",";

try {

    br = new BufferedReader(new FileReader(csvFile));
    while ((line = br.readLine()) != null) {

            // use comma as separator
                    if (line.charAt(0) == '"')
                    {
                        csvSplitBy = "\",";   
                    }
                    else
                    {
                        csvSplitBy = ",";
                    }
                    String[] movies = line.split(csvSplitBy);
          nameWithYear = ""+ movies[0]+" ("+movies[1]+")";
    }

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

return nameWithYear;
}

public static void main (String[] args)
{
CSVParsing obj = new CSVParsing();
String testString = obj.parseCSV();
}

}

Note that it is not 100% complete, I am testing it in small chunks to make sure it is doing everything as I want it to do. 请注意,它不是100%完整的,我正在对其进行小块测试,以确保它可以按照我的意愿进行所有操作。

UPDATE: Found out that it was related to blank year entries as part of the CSV. 更新:发现与CSV的空白年份条目有关。 How do I handle that? 我该如何处理? The program cuts off once it finds the year entry to be blank. 一旦发现年份输入为空白,该程序将关闭。

UPDATE 2: I solved it with my own but of research. 更新2:我通过自己的研究解决了问题。 I am taking the results after the split() and putting them into an ArrayList. 我在split()之后获取结果,并将其放入ArrayList中。 That way, I could handle blank entries in the year column by replacing them with another value. 这样,我可以通过用另一个值替换它们来处理year列中的空白条目。

I guess problem is with your input file.Make sure your input is not of the form 我猜问题出在您的输入文件中。请确保您的输入格式不正确
"cauchy hep(21\\10\\1991) ","cauchy hep" .Notice the space between ) and " remove the space if any since: if (line.charAt(0) == '"') { csvSplitBy = "\\",";
} else { csvSplitBy = ","; }
“ cauchy hep(21 \\ 10 \\ 1991)”,“ cauchy hep”。注意之间的空格,然后删除空格(如果有的if (line.charAt(0) == '"') { csvSplitBy = "\\",";
} else { csvSplitBy = ","; }
if (line.charAt(0) == '"') { csvSplitBy = "\\",";
} else { csvSplitBy = ","; }
if (line.charAt(0) == '"') { csvSplitBy = "\\",";
} else { csvSplitBy = ","; }

csvSplitBy equals "\\"," no space with the last character of string. If your file doesn't follow the pattern you specified whole line or whole file wil be treated as single string and will be stored in movies[0] .So there will no string at index 1 of movies that's why ArrayIndexOutOfBound. Remove the space Or you can include the space the beginning " \\"," again notice the space between " \\"," .It will solve the problem. csvSplitBy等于“ \\”,字符串的最后一个字符没有空格。如果您的文件不遵循该模式,则您指定的整个行或整个文件将被视为单个字符串,并将存储在movie [0]中。将在电影的索引1处没有字符串,这就是ArrayIndexOutOfBound的原因。删除空格或者您可以在开头以“ \\”,“包含空格,再次注意“ \\”,”之间的空格,这将解决问题。

split() method returns one element in the array this means that the separator does not exist in the line variable. split()方法返回数组中的一个元素,这意味着分隔符不存在于line变量中。

line.contains(csvSplitBy);// will be evaluated to false in case of one item is returned by split();

Make sure that the CSV file is comma separated .. or the data has more than one column (CSV formatted correctly ) 确保CSV文件以逗号分隔..或数据有多个列(CSV格式正确)

I hope this could help! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM