본문 바로가기
Language/java

[Java] 유용한 클래스 (java.util.Scanner 클래스)

by gamxong 2022. 7. 15.

 

Scanner(String source)
Scanner(File source)
Scanner(InputStream source)
Scanner(Readable source)
Scanner(ReadableByteChannel source)
Scanner(Path source)
Scanner useDelimiter(Pattern pattern)
Scanner useDelimiter(String pattern)

 

Scanner s = new Scanner(System.in);
String input = s.nextLine();

 

argArr = input.split(" +");  // 입력받은 내용의 공백을 구분자로 자른다.

★ 입력받은 라인의 단어는 공백이 여러 개 일 수 있으므로 정규식을 " +"로 하였다.

     ▶ '하나 이상의 공백' 을 의미

 

 

import java.util.Scanner;
import java.io.File;

class ScannerEx3 {
	public static void main(String[] args) throws Exception {
    	Scanner sc = new Scanner(new File("data3.txt"));
        int cnt = 0;
        int totalSum = 0;
        
        while(sc.hasNextLine()) {
        	String line = sc.nextLine();
            Scanner sc2 = new Scanner(line).useDelimiter(",");
            int sum=0;
            
            while(sc2.hasNextInt()) {
            	sum += sc2.nextInt();
            }
            System.out.println(line+ ", sum = " + sum);
            totalSum += sum;
            cnt++;
        }
        System.out.println("Line: " + cnt + ", Total: " + totalSum);
    }
}

라인별로 읽은 다음에 다시 ','를 구분자로 하는 Scanner를 이용해서 각각의 데이터를 읽어야 함.

 

 

댓글