I'm asking you a question about the sum using Java csv

Asked 2 years ago, Updated 2 years ago, 96 views

I have to write a program that calculates the total by reading the csv file below using scanner.

public class ScannerTest3 {

        public static void main(String[] args) throws Exception{

        Scanner sc1 = new Scanner(new File("C:\\Users\\dladnlwo\\Salaries.csv"));
        Scanner sc2 = null;

        int cnt = 0;
        int totalSum = 0;

    while(sc1.hasNextLine()) {

        String line=sc1.nextLine();
        sc2 = new Scanner(line).useDelimiter(" ");
        int sum = 0;

        while(sc2.hasNextInt()) {
            sum+=sc2.nextInt();
        }

        System.out.println(line+" sum="+sum);
        totalSum+=sum;
        cnt++;
        sc2.close();
    }
    System.out.println("Line : "+cnt+", Total : "+totalSum);
    sc1.close();
}

} I have to print out the values in the salary column, but if I turn it to the above code, only the value of sum = 0 comes out, and I don't know how to code it.

java scanner csv

2022-09-20 17:10

1 Answers

sc2 = new Scanner (line).useDelimiter(",");
            int sum = 0;
            int n;
            do {
                while(!sc2.hasNextInt()) {
                    sc2.next();
                }
                n = sc2.nextInt();
                sum = sum + n;
            } } while(sc2.hasNext());

/*
prof,B,56,49,Maile,186960 sum=187065
prof,B,56,49,Maile,1860 sum=1965
*/


2022-09-20 17:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.