코딩도 개발... 축구도 개발... 하...

2017년 8월 28일 월요일

11. 입력과 출력

1. 프로그램 실행시 한 번만 입력

package org.opentutorials.javatutorials.io;

// java util 안 에 있는 Scanner 객체를 사용하겠다. include 기능 같음  
import java.util.Scanner;
 
public class ScannerDemo {
 
    public static void main(String[] args) {
        // System.in 사용자가 입력한 값을 알아내는 역활
        // 파라미터로 파일명을 넘겨주면 파일을 읽는다.
        Scanner sc = new Scanner(System.in);
        
        // 사용자가 입력한 값을 받기전까지 대기
        int i = sc.nextInt();
        System.out.println(i*1000);
        sc.close();
    }
}

결과
1번 클릭 후 2번 영역에서 키보드로 숫자 5를 입력 할 경우 5 * 1000 이 실행 되어 결과 값 5000이 출력 된다

2. 키보드로 반복해서 입력 받기


package org.opentutorials.javatutorials.io;
 
import java.util.Scanner;
 
public class Scanner2Demo {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()) {
            System.out.println(sc.nextInt()*1000); 
        }
        sc.close();
    }
 
}

결과

실행 후 첨부파일과 같이 키보드 입력된 숫자 * 1000 계산된 결과가 출력된다.
숫자 외 입력시 프로그램이 종료된다.


3. 파일로 입력 값 받기 

파일 out.txt 미리 저장해 둔다. 저장 경로 첨부파일 참고

package org.opentutorials.javatutorials.io;
 
import java.util.Scanner;
import java.io.*;
 
public class Scanner3Demo {
 
    public static void main(String[] args) {
        try {
            File file = new File("out.txt");
            Scanner sc = new Scanner(file);
            while(sc.hasNextInt()) {
                System.out.println(sc.nextInt()*1000); 
            }
            sc.close();
        } catch(FileNotFoundException e){
            e.printStackTrace();
        }
         
    }
 
}


결과

111000
222000
out.txt 에 미리 등록된 111, 222 가 순차적으로 실행 되는 걸 확인 할 수 있다.

댓글 없음:

댓글 쓰기