JAVA_ 입력문

장성욱·2025년 5월 26일

JAVA

목록 보기
5/23

입력문 문법


import java.util.Scanner;

Scanner sc = new Scanner(System.in);

System.out.print("이름을 입력하세요 : ");
타입  변수명  = sc.next타입();
//String name = sc.nextLine();


System.out.println("이름 : " + name);

sc.next

sc.next 뒤는 문자 타입마다 다르게 붙음

  • 문자열(한 줄 전체) : nextLine();

  • 정수 : nextInt();

  • 실수 : nextDouble();

  • 단어 하나 : next();

응용문제

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("이름을 입력하세요 : ");
    String name = sc.nextLine();

    System.out.print("나이를 입력하세요 : ");
    int age = sc.nextInt();
    sc.nextLine();

    System.out.print("좋아하는 음식을 입력하세요 : ");
    String food = sc.nextLine();

    System.out.print("키를 입력하세요.(cm 단위) : ");
    double height = sc.nextDouble();

    System.out.println("==== 자기소개서 ====");
    System.out.println("이름 : " + name);
    System.out.println("나이 : " + age + "세");
    System.out.println("좋아하는 음식 : " + food);
    System.out.println("키 : " + height + "cm");

  }
}

sc.nextInt(); 후에
sc.nextLine();을 입력하지 않으면,
좋아하는 음식은 입력을 받지 않음


nextLine()만 단독으로 사용할 땐 문제가 없지만,
그 외 메서드 다음에는 sc.nextLine();을 한 줄 꼭 써줘야
그 다음 nextLine()이 제대로 작동함

profile
https://frost-puck-b0f.notion.site/B-2610fdaef71d80c49d1bccdcb575dcb5

0개의 댓글