JAVA

[ JAVA ] - 기본 입출력 받기

algml0703 2022. 8. 19. 23:01
반응형

 입력받은 값 출력하기

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
String str = sc.next();
//String str = sc.nextLine();
import java.util.Scanner;
// Scanner를 사용하기 위해 자바에 내장된 라이브러리를 가져옴.

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		// Scanner는 자바에서 제공하는 기본 라이브러리이다.
		System.out.print("정수를 입력하세요. : ");
		int i = sc.nextInt();
		System.out.println("입력된 정수 i : "+i);
		sc.close();
		// 프로그램 종료시 사용하며 입출력 기능이 안전하게 완전 종료되도록 한다. 
	}
}

문자열을 입력받을때는 sc.next()또는 sc.nextLine()을 이용한다.

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("당신의 이름은 무엇입니까?");
		String str = sc.nextLine();
		// sc.next()
		System.out.println(str);
		sc.close();
	}
}

 

file 읽어오기

File file = new File("[읽어올 파일명]");
Scanner sc = new Scanner(file);
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		File file = new File("input.txt");
		try {
			Scanner sc = new Scanner(file);
			while (sc.hasNextInt()) {
				System.out.println(sc.nextInt() * 100);
			}
			sc.close();
		}catch(FileNotFoundException e) {
			//e.printStackTrace();
			System.out.println("파일을 읽어오는 도중 오류가 발생하였습니다.");
		}
	}
}

출처

https://www.youtube.com/playlist?list=PLRx0vPvlEmdBjfCADjCc41aD4G0bmdl4R 

반응형

'JAVA' 카테고리의 다른 글

[ JAVA ] - 프로젝트 생성 후 hello world 찍기  (0) 2022.08.19
[ JAVA ] - 필드와 메서드  (0) 2022.08.19
[ JAVA ] - 기초 예제  (0) 2022.08.19
[ JAVA ] - 기본 개념  (0) 2022.07.27
[ JAVA ] - 자바 개발환경 구축 (feat mac) - 02  (0) 2022.07.24