본문 바로가기

Programming/자바

생활코딩 자바 - 입력과 출력(Input &Output, IO)

입력 (앱 실행 전)

public static void main(String[] args) {
System.out.println(args.length);  => args라는 배열이 담을 수 있는 값의 수 => 입력값의 수
}
}

 

void : 출력값 없음

main : 메소드

(String~) : 입력값 받는 매개변수(parameter)

 

  • 명령 프롬프트 이용

cd C:\~ : 해당 경로로 이동

cd .. : 상위 경로로 이동

dir : 디렉토리

java -cp : 실행

  ex. >java -cp bin org.opentutorials.javatutorials.io.InputDemo  => 0

      >java -cp bin org.opentutorials.javatutorials.io.InputDemo one two three four  => 4

 

 

  •  

public static void main(String[] args) {
for (String e : args) {
System.out.println(e);
}
}

 

one two three four 입력값 -> args -> args -> for문이 args 값을 하나하나 꺼내서 e에 담음 -> 출력

결과:

one

two

three

four

 

입력 (앱 실행 중)
  • 사용자 입력 받기

자바 라이브러리 - scanner(사용자가 입력한 값 알아냄) 사용

 

public static void main(String[] args) {
Scanner sc = new Scanner(System.in); =>(우항)파일이름을 입력하면 스캐너가 입력값 알아채서 (좌항) sc 변수에 담음
int i = sc.nextInt(); => (우항) 숫자만 입력 가능, 엔터 치면 실행시킴, (좌항) 변수 i에 입력값 담김
System.out.println(i*1000);
sc.close();

 

 

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
    while(sc.hasNextInt()) {  => 자바 재실행, 숫자-true값 반환, 숫자x-false값=종료
System.out.println(sc.nextInt()*1000);
}
sc.close();

 

 

여러 형태의 입출력
  •  

try {
File file = new File("out.txt"); 
Scanner sc = new Scanner(file); //out.txt 내용을 입력값으로
while(sc.hasNextInt()) {
System.out.println(sc.nextInt()*1000);
}
sc.close();
catch(FileNotFoundException e) {   ==> 예외
e.printStackTrace();

 

 

  • GUI