在Java中将字符串保存为整数数组

时间:2016-04-10 16:25:41

标签: java arrays

我的任务是从文本文件中读取匹配结果并将其放在array中。但是我必须使用匹配结果来计算团队绩效。为此,我必须将result数组中string的数据类型转换为int[]

任何人都可以帮我吗?

public LeagueMatch()
{

}
public LeagueMatch(String teamName, int[] result, String date, String opponent, int attendance,double ticketPrice,int awayFans) {
    this.teamName = teamName;
    this.result = result;
    this.date = date;
    this.opponent = opponent;
    this.attendance = attendance;
    this.ticketPrice = ticketPrice;
    this.awayFans = awayFans;
}

public LeagueMatch(String m)
{
    this.result = new int[2];
    String[] d = m.split(",");
    this.teamName=d[0];
    this.result=(d[1]); //there is an error here
    this.date=d[2];
    this.opponent=d[3];
    this.attendance=Integer.parseInt(d[4]);
    this.ticketPrice=Double.parseDouble(d[5]);
    this.awayFans=Integer.parseInt(d[6]);
}

2 个答案:

答案 0 :(得分:0)

我使用你给我的字符串

       String m = "Ashton Athletic,3-2,08/01/2011,Hounslow Harriers,10905,17.50,2013" ; 
   String[] d = m.split(",");
   String[] d1 = d[1].split("-") ;
   int[] result = new int[2];
   result[0]  = Integer.parseInt(d1[0]) ;
   result[1]  = Integer.parseInt(d1[1]) ;
   System.out.println(result[0]);
   System.out.println(result[1]);

这是我的例子,你可以修改它以适合你的情况

应该是

String[] d1 = d[1].split("-") ;
  this.result[0]  = Integer.parseInt(d1[0]) ;
   this.result[1]  = Integer.parseInt(d1[1]) ;

确保变量int [] result是初始化的

答案 1 :(得分:0)

尝试:this.result [0] = Integer.parseInt(d [1])