Allen's 데이터 맛집
[5] Java를 사용한 범죄 데이터 분석. TotalCrime 본문
Java를 사용하여 CSV 파일 데이터를 읽고, 특정 데이터를 합산하여 출력해 보겠습니다. 특히, TotalCrime 클래스를 사용하여 범죄 통계 데이터를 처리해 보겠습니다. 이 클래스는 CSV 파일에서 데이터를 읽어와 필요한 값을 변환하고, 이를 바탕으로 총 건수를 계산하여 출력합니다.
TotalCrime 클래스
아래는 TotalCrime 클래스의 전체 코드입니다. 이 코드는 CSV 파일을 읽어 데이터를 2차원 배열에 저장하고, 특정 열의 값을 합산하여 출력합니다.
import java.io.*;
public class TotalCrime {
public static void main(String[] args) {
int result = 0;
String[][] indat = new String[26][7];
try {
File csv = new File("path/to/your/csvfile.csv"); // CSV 파일 경로
BufferedReader br = new BufferedReader(new FileReader(csv));
String line = "";
int row = 0, i;
while ((line = br.readLine()) != null) {
String[] token = line.split(",", -1);
for (i = 0; i < 7; i++) {
indat[row][i] = (token[i]);
}
for (i = 0; i < 7; i++) {
System.out.print(indat[row][i] + ",");
}
System.out.println("");
row++;
}
// 총 건수 출력
for (int a = 2; a < 6; a++) {
int s = Integer.parseInt(indat[1][a]);
result += s;
}
System.out.println("발생건수 총합 : " + result);
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
코드 설명
- 변수 초기화 및 CSV 파일 읽기:
int result = 0;
String[][] indat = new String[26][7];
try {
File csv = new File("path/to/your/csvfile.csv"); // CSV 파일 경로
BufferedReader br = new BufferedReader(new FileReader(csv));
String line = "";
int row = 0, i;
while ((line = br.readLine()) != null) {
String[] token = line.split(",", -1);
for (i = 0; i < 7; i++) {
indat[row][i] = (token[i]);
}
for (i = 0; i < 7; i++) {
System.out.print(indat[row][i] + ",");
}
System.out.println("");
row++;
}
- indat 배열은 CSV 파일에서 읽어온 문자열 데이터를 저장합니다.
- CSV 파일을 읽어와 BufferedReader 객체를 사용하여 각 줄을 읽습니다.
- 각 줄을 쉼표(,)로 분리하여 indat 배열에 저장합니다.
- 읽은 데이터를 확인하기 위해 출력합니다.
2. 데이터 합산 및 결과 출력:
for (int a = 2; a < 6; a++) {
int s = Integer.parseInt(indat[1][a]);
result += s;
}
System.out.println("발생건수 총합 : " + result);
br.close();
- indat 배열의 특정 열의 값을 정수로 변환하여 합산합니다.
- 합산된 결과를 출력합니다.
3. 예외 처리:
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
파일을 읽는 도중 발생할 수 있는 예외를 처리합니다.
https://github.com/siilver94/Analyze-Data-in-CSV
GitHub - siilver94/Analyze-Data-in-CSV
Contribute to siilver94/Analyze-Data-in-CSV development by creating an account on GitHub.
github.com
728x90