2015-07-12 32 views
0

我有一个简单的格式,txt文件名为enroll.txt其中包含计算:for循环的任意时间

1997 2000 
cs108 40 35 
cs111 90 100 
cs105 14 8 
cs101 180 200 

第一行显示的岁月类

第二行第一列显示了班级名称,以下两列显示了第一行中提到的班级中的学生人数。

ex)1997年,在班级cs108有40名学生。

我想要的结果:代码打印使用如下 (I)分裂(II)parseInt函数(三)环

student totals: 
    1997: 324 
    2000: 343 

但这种代码也应该多少年的工作(例如,如果我的学生人数为四年,而不是两年,代码仍然会给我类似的输出,比如说学生总数为1997,2000,2001,2002等。)

我到目前为止:

import java.util.*; 
    import java.io.*; 

    public class ProcessCourses{ 
     public static void main(String[] args) throws FileNotFoundException{ 

     Scanner console = new Scanner(System.in); 
     String fileName = console.nextLine(); 

     Scanner input = new Scanner(new File(fileName)); 

     while(input.hasNextLine()){ 
      String line = input.nextLine(); 
      String[] arr = line.split(" "); 


      //......???? 


     } 
    } 
} 

//里面会发生什么?

+0

数字之间是否有一致的分隔符? – Karthik

+0

是的,一个空格(“”) – CMSC

回答

2

所以你有多年的第一线,第一阅读:

 Scanner input = new Scanner(new File(fileName)); 
     String str = input.nextLine(); 
     String[] years = str.split(" "); 

现在已经设置了一个学生的信息,

 int[] total = new int[years.length]; 
     while(input.hasNextLine()){ 
     String line = input.nextLine(); 
     String[] strength = line.split(" "); 
     int len = strength.length; // no of entries which includes course id + "years" no.of numbers. 

     for(int i=1;i<len;i++){ // from 1 because you don't care the course id 
      total[i-1] = total[i-1] + Integer.parseInt(strength[i]); 
     } 
    } 

然后,只需打印:

for(int i=0;i<years.length;i++){ 
     System.out.println(years[i]+ " : " + total[i]); 
    }