java - Calculating Average from a CSV File -


i have csv file, format follows:

city,job,salary delhi,doctors,500 delhi,lawyers,400 delhi,plumbers,100 london,doctors,800 london,lawyers,700 london,plumbers,300 tokyo,doctors,900 tokyo,lawyers,800 tokyo,plumbers,400 lawyers,doctors,300 lawyers,lawyers,400 lawyers,plumbers,500 hong kong,doctors,1800 hong kong,lawyers,1100 hong kong,plumbers,1000 moscow,doctors,300 moscow,lawyers,200 moscow,plumbers,100 berlin,doctors,800 berlin,plumbers,900 paris,doctors,900 paris,lawyers,800 paris,plumbers,500 paris,dog catchers,400

i want find average of total salaries.

this code:

` import java.io.*;

public class {

public static void main(string args[]) { a= new a(); a.run(); }  public void run() { string csv="c:\\users\\dipayan\\desktop\\salaries.csv";         bufferedreader br = null; string line = ""; int sum=0; int count=0; //string a=new string();           try {              br = new bufferedreader(new filereader(csv));             try {                 while ((line = br.readline()) != null) {                          // use comma separator                     string[] country = line.split(",");                     int sal=integer.parseint(country[2]);                     sum=sum+sal;                          count++;                 //system.out.println("salary [job= " + country[0]                                    //        + " , salary=" + country[2] + "]");                  }             } catch (numberformatexception | ioexception e) {                 system.out.println("na");                 e.printstacktrace();             }           } catch (filenotfoundexception e) {             e.printstacktrace();         }           system.out.println(sum/count);           system.out.println("done");       }      }`  

but, showing error:

java.lang.numberformatexception: input string: "salary" @ java.lang.numberformatexception.forinputstring(unknown source) @ java.lang.integer.parseint(unknown source) @ java.lang.integer.parseint(unknown source) @ a.run(a.java:30) @ a.main(a.java:9) exception in thread "main" java.lang.arithmeticexception: / 0 @ a.run(a.java:46) @ a.main(a.java:9)`

is there better or short code parse csv file.

skip first line of csv file. additional

br.readline() 

before while.

you might want add format checks sure file reading in correct format.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -