gpt4 book ai didi

java - 从文件读取时的system.arraycopy - java

转载 作者:行者123 更新时间:2023-12-01 22:46:25 26 4
gpt4 key购买 nike

我需要从文件中读取数据,格式为:int, Name nameClass, String, String, String, Scores [int,int,int,int,int],例如

150,约翰·史密斯,美国,活跃,专业,3,4,3,4,4

运行代码后出现以下错误

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at f1_final.CompetitorList.processLine(CompetitorList.java:184)
at f1_final.CompetitorList.readFile(CompetitorList.java:149)
at f1_final.FileWriterComp.main(FileWriterComp.java:14)

我发现这是因为我试图将 int 复制到字符串。我该如何解决这个问题?

private void processLine(String line)   {
String compNo = "";

try {
String [] parts = line.split(",");
nameClass compName = new nameClass(parts[1], parts[2]);
compNo = parts[0];
compNo = compNo.trim();


String compCountry = parts[3];
String compLevel = parts [4];
String compActive = parts[5];

int compNumber = Integer.parseInt(compNo);
int compScoreLength = parts.length-6;
int cScore[] = new int[compScoreLength];

System.arraycopy(parts, 6, cScore, 0, compScoreLength); // this line is causing problems which I wasnt able to fix. The program is unable to read arrays from file.

// int[]cScore = new int [compScoreLength];
// for(int i=0 ; i< compScoreLength ; i++)
// cScore[i] = parts[6].charAt(i)-'0';


Competitor c = new Competitor(compNumber, compName, compCountry, compLevel, compActive, cScore);
this.addOneCompetitor(c);
}

最佳答案

stach 跟踪清楚地表明 java.lang.String.charAt(String.java:658) 中存在异常,该异常是在您取消注释的部分中调用的。看来你取消注释后没有重建。请注意,System.arraycopy() 仅当源数组和目标数组具有相同类型时才有效。

您必须手动转换每个元素:

  int[]cScore = new int [compScoreLength];
for(int i=0 ; i< compScoreLength ; i++)
cScore[i] = Integer.parseInt(parts[6 + i]);

在此示例中,您有 parts[6] = "3"parts[7] = "4"parts[8] = "3 “,...,它们都是一个 String

关于java - 从文件读取时的system.arraycopy - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472474/

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