Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- counldn't have
- 명절 표현
- 명세기반테스트
- 변수
- I'm glad
- happen to
- if조건절
- sort함수
- java
- keep -ing
- continue to
- 게임QA
- 제5인격
- by until
- 코로나19
- by any chance
- metascore
- end up ing
- know
- ISTQB
- C++
- relif
- gameQA
- Realtime Rendering
- might have p.p
- for ing
- html
- 형변환
- UE4
- it's a good thing
Archives
- Today
- Total
Records rather than Memories
입력과 출력 본문
String[] args
1
2
3
4
5
|
class InputDemo{
public static void main(String[] args){
System.out.println(args.length);
}
}
|
cs |
main은 자바에서 특별한 메소드이다.
실행하면 main 메소드가 호출되고 구동된다.
이때 String[] args는 parameter로 동작한다.
- String[]은 문자열을 담고 있는 배열
- args.length는 배열의 길이를 가져오는 함수
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package javatutorials.io;
public class InputForeachDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(String e : args){
System.out.println(e);}
}
}
|
cs |
for-each 구문을 이용해서 변수 args에 담긴 값을 한줄씩 출력
* Run configuration 어떻게 실행할지 환경을 저장 : name, argument / 일종의 초기값을 주는 것
사용자의 입력 받기
자바에서 제공하는 라이브러리 중에 scanner를 이용하면 사용자의 입력을 받을 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package javatutorials.io;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println(i*1000);
sc.close();
}
}
|
cs |
다음 예제는 입력한 숫자의 1000배가 출력되는 코드이다.
sc.nextInt()가 실행되면 i에 값(숫자)을 입력할 때까지 대기한다.
키보드로 데이터를 입력하고 공백문자인 엔터를 누르면 i에 값이 담긴다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package javatutorials.io;
import java.util.Scanner;
public class ScannerDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()) {
System.out.println(sc.nextInt()*1000);
}
sc.close();
}
}
|
cs |
.hasNextInt() 메소드가 실행되면 일단 정지
사용자가 입력한 값에 엔터를 치면 진행, 만약 숫자라면 true / 아니라면 false 입력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package javatutorials.io;
import java.util.Scanner;
import java.io.*;
public class ScannerDemo3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
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();
}
}
}
|
cs |
"out.txt" 경로 안에 있는 메모장 파일
스캐너에게 사용자가 입력한 값을 얻어와라.
여기서 파일을 지정하면 out.txt에 있는 내용을 가져와라 라고 지시하는 것
* try { } catch(FileNotFoundException e) 파일을 찾을 수 없다면 e.printStackTrace();
Comments