Scanner

next()

๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ํ•œ ๋‹จ์–ด ๋˜๋Š” ํ•œ ๋ฌธ์ž์”ฉ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ๋ฒ„ํผ์— ์ž…๋ ฅ๋œ ๋ฌธ์ž๋‚˜ ๋ฌธ์ž์—ด์—์„œ ๊ณต๋ฐฑ ์ „๊นŒ์ง€์˜ ๋‹จ์–ด๋ฅผ ์ฝ๋Š”๋‹ค. ๊ฐœํ–‰ ๋ฌธ์ž๋ฅผ ๊ฐ€์ ธ์˜ค์ง€ ์•Š๋Š”๋‹ค.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = scan.next();
        System.out.println(str);
    }

nextLine()

๋ฌธ์ž ๋˜๋Š” ์—”ํ„ฐ๋ฅผ ์น˜๊ธฐ ์ „๊นŒ์ง€์˜ ๋ฌธ์žฅ ์ „์ฒด๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ๋ฒ„ํผ์— ์ž…๋ ฅ๋œ ๋ฌธ์ž์—ด์„ ๊ฐœํ–‰ ๋ฌธ์ž๊นŒ์ง€ ๋‹ค ๊ฐ€์ ธ์˜จ๋‹ค.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        System.out.println(str);
    }
}

nextInt()

int๋ฅผ ์ž…๋ ฅ ๋ฐ›์„ ๋•Œ๋Š” nextInt ๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•œ๋‹ค.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        System.out.println(num);
    }
}

ex) Hello World ์ž…๋ ฅ
next() : Hello๋งŒ ์ถœ๋ ฅ
nextLine() : Hello World ์ถœ๋ ฅ

nextInt() ์‚ฌ์šฉ ํ›„ nextLine() ์‚ฌ์šฉ ์‹œ ๋ฌธ์ œ ๋ฐœ์ƒ

  • nextInt()๋Š” ๊ฐœํ–‰ ๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•˜์ง€ ์•Š๋Š”๋‹ค. ๊ทธ๋ž˜์„œ ๋ฒ„ํผ์— ๊ฐœํ–‰ ๋ฌธ์ž๊ฐ€ ๋‚จ์•„์žˆ๊ฒŒ ๋œ๋‹ค.
  • ์—ฌ๊ธฐ์„œ, nextLine()์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋ฉด ๊ฐœํ–‰ ๋ฌธ์ž๋ฅผ ๋งŒ๋‚˜์„œ ๊ฐœํ–‰ ๋ฌธ์ž๋ฅผ ๋ฐ›๊ฒŒ ๋œ๋‹ค.
  • ๋”ฐ๋ผ์„œ ์›ํ•˜๋Š” ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ๋ฐ›์ง€ ๋ชปํ•  ์ˆ˜ ์žˆ๋‹ค.

๋ฌธ์ œ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

  • nextInt()์™€ nextLine() ์‚ฌ์ด์— nextLine()์„ ํ•˜๋‚˜ ์ถ”๊ฐ€ํ•˜์—ฌ ๊ฐœํ–‰ ๋ฌธ์ž๋ฅผ ๋ฒ„ํผ์—์„œ ์—†์• ์ฃผ๋ฉด ์›ํ•˜๋Š” ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String nextStr = scan.next();
        System.out.println(nextStr);
        
        String nextLineStr = scan.nextLine();
        System.out.println(nextLineStr);
    }
}

๊ฒฐ๊ณผ)

Hello World
Hello
 World
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String nextStr = scan.next();
        System.out.println(nextStr);

        scan.nextLine();
        
        String nextLineStr = scan.nextLine();
        System.out.println(nextLineStr);
    }
}

๊ฒฐ๊ณผ)

Hello World
Hello
World
World

์ž…๋ ฅ Hello World ๋จผ์ €ํ•ด์ฃผ๋ฉด Hello ์ถœ๋ ฅ ํ›„ ๋˜ ์ž…๋ ฅ์„ ๋ฐ›๋Š”๋‹ค.
scan.nextLine(); ์ด๊ฒŒ ๋ฒ„ํผ์— ๋‚จ์•„์žˆ๋Š” ๊ฐœํ–‰ ๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•ด์ค€๊ฒƒ ๊ฐ™๋‹ค.
World ์ž…๋ ฅ ํ›„ World ์ถœ๋ ฅ๋จ.

์ฐธ๊ณ  ๋ธ”๋กœ๊ทธ: c-king.tistory

Leave a comment