Java 1 - Using scanner
Java의 scanf() 역할을 하는 것은 scanner 클래스이다. C에서 input, output을 사용하기 위해 <stdio.h>를 헤더에 서술하는 것 처럼, scanner 클래스도 java.util.Scanner를 import 해야 사용할 수 있다.
java는 C++과 함께 대표적인 Object Oriented Programming language이다. 따라서 scanner를 사용하기 전에, 해당 클래스의 객체를 생성하고 사용하여야 한다.
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);//새 스캐너의 컨스트럭터에는 항상 system.in을 써줘야 한다.
System.out.print("Write x value");
String strX= scanner.nextLine(); // nextline은 다음줄을 엔터가 입력될때까지 받는다. 단, 버퍼에 엔터 등이 남아있으면 입력되지 않고 넘어가는 경우가 있기 때문에 주의해야한다.
System.out.println(strX);
scanner.close(); // 스캐너를 다 쓰면 항상 닫아줘야 한다.
}
}
printf의 역할을 하는 것은 System.out.print 구문으로, 줄바꿈의 여부에 따라 println(줄바꿈), print(줄 바꾸지 않음) 등을 사용하면 된다.
import java.util.Scanner;//스캐너를 쓰기 위한 헤더
public class prob1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Circle");
String strx = scanner.nextLine(); // 다음줄을 받아 스트링에 전부 저장한다.
String stry = scanner.nextLine();
String strr = scanner.nextLine();
System.out.println("point");
String stra = scanner.nextLine();
String strb = scanner.nextLine();
int x =Integer.parseInt(strx); // 스트링으로 입력받은 것들의 값을 인트값으로 변환하여 각 변수에 저장한다.
int y =Integer.parseInt(stry);
int r =Integer.parseInt(strr);
int a =Integer.parseInt(stra);
int b =Integer.parseInt(strb);
if((x-a)*(x-a)+(y-b)*(y-b)<=r*r){
System.out.println("the point is inside of circle");
}
else{
System.out.println("the point is outide of circle");
}
scanner.close();
}
}
java는 parse명령어로 string input을 원하는 primitive 타입으로 변경할 수 있다.
댓글
댓글 쓰기