728x90
목차
1. 입력
■ 문자열
- 여러 문자를 하나로 묶은 것
- 문자열은 기본 자료형에 속하지 않으며 참조 자료형임
- API에서 제공하는 String class를 이용
- 문자와 문자열은 + 연산자로 합칠 수 있음
- 문자열과 기본 자료형을 + 연산자로 연산 시 기본 자료형은 문자열로 업 캐스팅됨
■ scanner
- scanner는 문자를 입력받아 사용할 수 있는 라이브러리
- scanner 사용 시 nextLine()을 제외한 나머지는 띄어쓰기를 하면 엔터로 사용됨
- nextLine()을 제외하고 나머지는 문자 입력 후 엔터 시 엔터가 버퍼에 남아 있음
- nextLine()을 제외하고 버퍼에 엔터가 남아있기 때문에 엔터를 처리해주기 위해 nextLine()을 호출해 허공에 날려줘야 함
2. 예시
■ Input1
package j05_입력;
import java.util.Scanner;
public class Input1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
// 함수의 호출(scanner.nextInt())을 먼저 진행하기 때문에 입력을 먼저하고 출력됨
System.out.println("입력값 : " + scanner.nextInt());
System.out.print("입력1 : ");
a = scanner.nextInt();
System.out.print("입력2 : ");
b = scanner.nextInt();
System.out.print("입력3 : ");
c = scanner.nextInt();
System.out.print("입력4 : ");
d = scanner.nextInt();
System.out.print("입력5 : ");
e = scanner.nextInt();
}
}
■ Input2
package j05_입력;
import java.util.Scanner;
public class Input2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// nextLine()은 띄어쓰기, 엔터 포함, nextLine()외에 띄어쓰기를 허용 안함
System.out.print("문자열1 : ");
String str1 = scanner.nextLine();
// 띄워쓰기 미포함, 띄어쓰기가 엔터로 사용됨
System.out.print("문자열2 : ");
String str2 = scanner.next();
System.out.print("정수 : ");
int number1 = scanner.nextInt();
System.out.print("실수 : ");
double number2 = scanner.nextDouble();
System.out.println("문자열1 : " + str1);
System.out.println("문자열2 : " + str2);
System.out.println("정수 : " + number1);
System.out.println("실수 : " + number2);
}
}
■ Input3
package j05_입력;
import java.util.Scanner;
public class Input3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = null;
int age = 0;
String address = null;
String phone = null;
System.out.print("이름 : ");
name = scanner.next();
System.out.print("나이 : ");
age = scanner.nextInt();
// 버퍼에 남아있는 엔터를 처리해주기 위하여 nextLine()을 한번 더 적어 주어 엔터를 허공에 날림
scanner.nextLine();
System.out.print("주소 : ");
address = scanner.nextLine();
System.out.print("연락처 : ");
phone = scanner.next();
System.out.println("사용자의 이름은 " + name + "이고 나이는 " + age + "살입니다.");
System.out.println("주소는 " + address + "에 거주중입니다.");
System.out.println("연락처는 " + phone + " 입니다.");
}
}
■ Input4
package j05_입력;
import java.util.Scanner;
public class Input4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = 0;
int b = 0;
int c = 0;
int max = 0;
int min = 0;
System.out.print("정수 3개 입력 : ");
a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();
System.out.println("a : " + a);
System.out.println("b : " + b);
System.out.println("c : " + c);
// a 값을 먼저 max에 대입
max = a;
// b와 max 비교
max = b > max ? b : max;
// c와 max 비교
max = c > max ? c : max;
min = a;
min = b < min ? b : min;
min = c < min ? c : min;
System.out.println("최대값 : " + max);
System.out.println("최소값 : " + min);
}
}