수색…


통사론

  • 스캐너 스캐너 = 새 스캐너 (소스 소스);
  • 스캐너 스캐너 = 새 스캐너 (System.in);

매개 변수

매개 변수 세부
출처 Source는 String, File 또는 임의의 종류의 InputStream 중 하나 일 수 있습니다.

비고

Scanner 클래스는 Java 5에서 소개되었습니다. Java 6에서는 reset() 메소드가 추가되었으며 (새로운) Path 인터페이스와의 상호 운용성을 위해 Java 7에는 몇 가지 새로운 생성자가 추가되었습니다.

스캐너를 사용하여 시스템 입력 읽기

Scanner scanner = new Scanner(System.in); //Scanner obj to read System input
String inputTaken = new String();
while (true) {
    String input = scanner.nextLine(); // reading one line of input
    if (input.matches("\\s+"))         // if it matches spaces/tabs, stop reading
        break;
    inputTaken += input + " ";
}
System.out.println(inputTaken);

스캐너 개체는 키보드에서 입력을 읽도록 초기화됩니다. 그래서 keyboar에서 아래의 입력을 위해, Reading from keyboard 출력을 생성합니다.

Reading
from
keyboard
  //space

Scanner를 사용하여 파일 입력 읽기

Scanner scanner = null;
try {
    scanner = new Scanner(new File("Names.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (Exception e) {
    System.err.println("Exception occurred!");
} finally {
    if (scanner != null)
        scanner.close();
}

여기서 Scanner 객체는 텍스트 파일의 이름을 포함하는 File 객체를 입력으로 전달하여 생성됩니다. 이 텍스트 파일은 File 객체에 의해 열리고 다음 행의 scanner 객체에 의해 읽혀집니다. scanner.hasNext() 는 텍스트 파일에 다음 데이터 행이 있는지 확인합니다. 이를 while 루프와 결합하면 Names.txt 파일의 모든 데이터 행을 반복 할 수 있습니다. 데이터 자체를 검색하기 위해 nextLine() , nextInt() , nextBoolean() 등의 메서드를 사용할 수 있습니다. 위 예제에서 scanner.nextLine() 이 사용되었습니다. nextLine() 은 텍스트 파일의 다음 행을 참조하고이를 scanner 객체와 결합하면 행의 내용을 인쇄 할 수 있습니다. 스캐너 객체를 닫으려면 .close() 합니다.

자바 (Java 7 이상)에서 리소스를 사용하여 try를 사용하면 다음과 같이 위에서 언급 한 코드를 우아하게 작성할 수있다.

try (Scanner scanner = new Scanner(new File("Names.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (Exception e) {
    System.err.println("Exception occurred!");
}

Scanner를 사용하여 전체 입력을 String으로 읽습니다.

Scanner 를 사용하여 \Z (전체 입력)를 구분 기호로 사용하여 입력 텍스트의 모든 텍스트를 문자열로 읽을 수 있습니다. 예를 들어, 텍스트 파일의 모든 텍스트를 한 줄로 읽는 데 사용할 수 있습니다.

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

Scanner를 사용하여 파일 입력 읽기 예제에 설명 된 것처럼 스캐너가 IoException throw 될 수있는 IoException 을 잡아야합니다.

사용자 정의 구분 기호 사용

.useDelimiter(",") 와 함께 Scanner에서 사용자 정의 구분 기호 (정규식 .useDelimiter(",") 를 사용하여 입력 내용을 읽는 방법을 결정할 수 있습니다. 이것은 String.split(...) 와 비슷하게 작동합니다. 예를 들어 Scanner 를 사용하여 문자열의 쉼표로 구분 된 값 목록에서 읽을 수 있습니다.

Scanner scanner = null;
try{
    scanner = new Scanner("i,like,unicorns").useDelimiter(",");;
    while(scanner.hasNext()){
        System.out.println(scanner.next());
    }
}catch(Exception e){
    e.printStackTrace();
}finally{
    if (scanner != null)
        scanner.close();
}

이렇게하면 입력의 모든 요소를 ​​개별적으로 읽을 수 있습니다. 이것을 사용하여 CSV 데이터를 구문 분석 하지 말고 올바른 CSV 구문 분석기 라이브러리를 사용하십시오 (다른 용도는 JavaCSV 구문 분석기 참조).

작업에 대해 가장 일반적으로 묻는 일반 패턴

다음은 java.util.Scanner 클래스를 올바르게 사용하여 System.in 에서 사용자 입력을 대화식으로 올바르게 읽는 방법입니다 (특히 stdin 이라고도 함, 특히 C, C ++ 및 Unix 및 Linux뿐만 아니라 다른 언어에서도 사용됨). 그것은 관용적으로 요구되는 가장 일반적인 것들을 보여줍니다.

package com.stackoverflow.scanner;

import javax.annotation.Nonnull;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;

import static java.lang.String.format;

public class ScannerExample
{
    private static final Set<String> EXIT_COMMANDS;
    private static final Set<String> HELP_COMMANDS;
    private static final Pattern DATE_PATTERN;
    private static final String HELP_MESSAGE;

    static
    {
        final SortedSet<String> ecmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        ecmds.addAll(Arrays.asList("exit", "done", "quit", "end", "fino"));
        EXIT_COMMANDS = Collections.unmodifiableSortedSet(ecmds);
        final SortedSet<String> hcmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        hcmds.addAll(Arrays.asList("help", "helpi", "?"));
        HELP_COMMANDS = Collections.unmodifiableSet(hcmds);
        DATE_PATTERN = Pattern.compile("\\d{4}([-\\/])\\d{2}\\1\\d{2}"); // http://regex101.com/r/xB8dR3/1
        HELP_MESSAGE = format("Please enter some data or enter one of the following commands to exit %s", EXIT_COMMANDS);
    }

    /**
     * Using exceptions to control execution flow is always bad.
     * That is why this is encapsulated in a method, this is done this
     * way specifically so as not to introduce any external libraries
     * so that this is a completely self contained example.
     * @param s possible url
     * @return true if s represents a valid url, false otherwise
     */
    private static boolean isValidURL(@Nonnull final String s)
    {
        try { new URL(s); return true; }
        catch (final MalformedURLException e) { return false; }
    }

    private static void output(@Nonnull final String format, @Nonnull final Object... args)
    {
        System.out.println(format(format, args));
    }

    public static void main(final String[] args)
    {
        final Scanner sis = new Scanner(System.in);
        output(HELP_MESSAGE);
        while (sis.hasNext())
        {
            if (sis.hasNextInt())
            {
                final int next = sis.nextInt();
                output("You entered an Integer = %d", next);
            }
            else if (sis.hasNextLong())
            {
                final long next = sis.nextLong();
                output("You entered a Long = %d", next);
            }
            else if (sis.hasNextDouble())
            {
                final double next = sis.nextDouble();
                output("You entered a Double = %f", next);
            }
            else if (sis.hasNext("\\d+"))
            {
                final BigInteger next = sis.nextBigInteger();
                output("You entered a BigInteger = %s", next);
            }
            else if (sis.hasNextBoolean())
            {
                final boolean next = sis.nextBoolean();
                output("You entered a Boolean representation = %s", next);
            }
            else if (sis.hasNext(DATE_PATTERN))
            {
                final String next = sis.next(DATE_PATTERN);
                output("You entered a Date representation = %s", next);
            }
            else // unclassified
            {
                final String next = sis.next();
                if (isValidURL(next))
                {
                    output("You entered a valid URL = %s", next);
                }
                else
                {
                    if (EXIT_COMMANDS.contains(next))
                    {
                        output("Exit command %s issued, exiting!", next);
                        break;
                    }
                    else if (HELP_COMMANDS.contains(next)) { output(HELP_MESSAGE); }
                    else { output("You entered an unclassified String = %s", next); }
                }
            }
        }
        /*
           This will close the underlying Readable, in this case System.in, and free those resources.
           You will not be to read from System.in anymore after this you call .close().
           If you wanted to use System.in for something else, then don't close the Scanner.
        */
        sis.close();
        System.exit(0);
    }
}

명령 행에서 int 읽기

import java.util.Scanner;

Scanner s = new Scanner(System.in);
int number = s.nextInt();

명령 줄에서 int를 읽으려면이 스 니펫을 사용하십시오. 먼저 명령 줄에서 프로그램을 시작할 때 기본적으로 명령 줄 인 System.in을 수신하는 Scanner 개체를 만들어야합니다. 그런 다음 Scanner 객체를 사용하여 사용자가 명령 줄에 전달한 첫 번째 int를 읽고 변수 번호에 저장합니다. 이제 저장된 int를 사용하여 원하는 모든 작업을 수행 할 수 있습니다.

조심스럽게 스캐너 닫기

생성자에 대한 System.in 매개 변수와 함께 스캐너를 사용하는 경우, 스캐너를 닫으면 InputStream을 닫을 것임을 알아야합니다. 그 다음에는 모든 입력을 읽으려고 시도합니다. 스캐너 객체)는 java.util.NoSuchElementException 또는 java.lang.IllegalStateException throw합니다.

예:

    Scanner sc1 = new Scanner(System.in);
    Scanner sc2 = new Scanner(System.in);
    int x1 = sc1.nextInt();
    sc1.close();
    // java.util.NoSuchElementException
    int x2 = sc2.nextInt();
    // java.lang.IllegalStateException
    x2 = sc1.nextInt();


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow