programing

Scanner 클래스의 next () 및 nextLine () 메서드의 차이점은 무엇입니까?

nasanasas 2020. 10. 29. 08:13
반응형

Scanner 클래스의 next () 및 nextLine () 메서드의 차이점은 무엇입니까?


next()의 주요 차이점은 무엇입니까 nextLine()?
내 주요 목표는 모든 소스 (예 : 파일)에 Scanner"연결"될 수 있는를 사용하여 모든 텍스트를 읽는 것입니다 .

어떤 것을 선택해야하며 그 이유는 무엇입니까?


나는 항상 입력을 읽고 nextLine()문자열을 구문 분석하는 것을 선호 합니다.

사용 next()하면 공백 앞에 오는 것만 반환합니다. nextLine()현재 라인을 반환 한 후 자동으로 스캐너를 아래로 이동합니다.

에서 분석 데이터에 대한 유용한 도구가 nextLine()될 것이다 str.split("\\s+").

String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces

Scanner 클래스 또는 String 클래스에 대한 자세한 내용은 다음 링크를 참조하십시오.

스캐너 : http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

문자열 : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html


next()공간까지만 입력을 읽을 수 있습니다. 공백으로 구분 된 두 단어를 읽을 수 없습니다. 또한 next()입력을 읽은 후 커서를 같은 줄에 놓습니다.

nextLine()단어 사이의 공백을 포함하여 입력을 읽습니다 (즉, 줄 끝까지 읽음 \n). 입력을 읽으면 nextLine()커서를 다음 줄에 놓습니다.

전체 줄을 읽으려면 nextLine().


JavaDoc에서 :

  • A Scanner는 기본적으로 공백과 일치하는 구분 기호 패턴을 사용하여 입력을 토큰으로 나눕니다.
  • next():이 스캐너에서 다음 완전한 토큰을 찾아 반환합니다.
  • nextLine(): 현재 줄을 지나서이 스캐너를 진행하고 건너 뛴 입력을 반환합니다.

따라서의 경우 "small example<eol>text" next()"small" nextLine()을 반환하고 "small example"을 반환해야합니다.


next ()를 제외하고는 nextLine ()이 전체 라인을 스캔하는 공간까지만 스캔한다는 점 nextLine ()이 완전한 토큰을 기다리지 않고 '\ n'일 때 완전한 토큰을 얻을 때까지 대기 한다는 것입니다. (즉, Enter 키를 누르면) 스캐너 커서가 다음 줄로 이동하고 건너 뛴 이전 줄로 돌아갑니다. 완전한 입력을 제공했는지 여부를 확인하지 않습니다. 심지어 next ()가 빈 문자열을 사용하지 않는 빈 문자열을 사용합니다.

public class ScannerTest {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int cases = sc.nextInt();
        String []str = new String[cases];
        for(int i=0;i<cases;i++){
            str[i]=sc.next();
        }
     }

}

for 루프에서 next ()와 nextLine ()을 변경하여이 프로그램을 시도하고, 아무 입력없이 엔터 키 인 '\ n'을 계속 누르면 주어진 수의 경우를 누른 후 종료되는 nextLine () 메소드 를 사용할 수 있습니다 . 로 다음 () doesnot 종료 의 경우, 지정된 번호를 여기에 당신이 제공 전까지 입력합니다.


이 질문에서 핵심은 메서드가 중지 될 위치와 메서드를 호출 한 후 커서가있는 위치를 찾는 것입니다. 모든 메소드는 커서 위치와 다음 기본 구분 기호 (공백, 탭, \ n--Enter를 눌러 생성됨) 사이의 정보를 읽고 (공백을 포함하지 않음) 구분 기호 앞에 커서가 멈 춥니 다 (nextLine () 제외). 커서 위치와 \ n 사이의 정보 (구분자로 만든 공백 포함)를 읽고 커서가 \ n 뒤에 멈 춥니 다.

예 : (|는 현재 커서 위치를, _는 공백을, 스트림은 굵은 글씨로 호출하는 방법으로 얻은 정보)

23_24_25_26_27 \ n

nextInt (); 호출 23 읽기 | _24_25_26_27 \ n

nextDouble (); 호출 23_ 읽기 (24) _25_26_27 \ n을 |

next (); 호출 23_24_ 25 읽기 | _26_27 \ n

nextLine (); 호출 23_24_25 _26_27 읽기 \ n |

그런 다음 요구 사항에 따라 메서드를 호출해야합니다.


에서 의 javadoc

next () 지정된 문자열에서 생성 된 패턴과 일치하면 다음 토큰을 반환합니다. nextLine () 현재 행을지나이 스캐너를 진행시키고 건너 뛴 입력을 리턴합니다.

당신이 선택하는 것은 당신의 필요에 가장 잘 맞는 것에 달려 있습니다. 내가 전체 파일을 읽는다면 모든 파일을 가질 때까지 nextLine으로 갈 것입니다.


간단히 말해서 길이 t의 문자열 배열을 입력하는 경우 Scanner # nextLine ()은 t 줄을 예상하고 문자열 배열의 각 항목은 Enter 키로 다른 항목과 구분되며 Scanner # next ()는 다음까지 입력을 계속받습니다. Enter 키를 누르지 만 공백으로 구분 된 배열 내부에 문자열 (단어)을 저장합니다.

다음 코드 스 니펫을 살펴 보겠습니다.

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.next();
    }

IDE에서 코드 스 니펫 위를 실행할 때 (문자열 길이 2에 대해 말할 수 있음) 내 문자열을 다음과 같이 입력하는지 여부는 중요하지 않습니다.

입력 :-abcd abcd 또는

다음과 같이 입력하십시오.

abcd

abcd

출력은 abcd와 같습니다.

abcd

그러나 같은 코드에서 next () 메서드를 nextLine ()으로 대체하면

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.nextLine();
    }

그런 다음 프롬프트에 다음과 같이 입력하면-abcd abcd

출력은 다음과 같습니다.

abcd abcd

프롬프트에 abcd로 입력을 입력하면 (그리고 Enter 키를 눌러 다른 줄에 다음 abcd를 입력하면 입력 프롬프트가 종료되고 출력이 표시됩니다)

출력은 다음과 같습니다.

abcd


스캐너 설명서에서 :

Scanner는 기본적으로 공백과 일치 하는 구분 기호 패턴을 사용하여 입력을 토큰으로 나눕니다 .

next ()에 대한 문서에서 :

완전한 토큰 앞에는 구분 기호 패턴과 일치하는 입력이옵니다.


next () 및 nextLine () 메서드는 Scanner와 연결되어 있으며 문자열 입력을 가져 오는 데 사용됩니다. 그들의 차이점은 ...

next ()는 공백까지만 입력을 읽을 수 있습니다. 공백으로 구분 된 두 단어를 읽을 수 없습니다. 또한 next ()는 입력을 읽은 후 같은 줄에 커서를 놓습니다.

nextLine ()은 단어 사이의 공백을 포함하여 입력을 읽습니다 (즉, 줄 끝까지 읽음 \ n). 입력이 읽 히면 nextLine ()은 커서를 다음 줄에 놓습니다.

import java.util.Scanner;

public class temp
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter string for c");
        String c=sc.next();
        System.out.println("c is "+c);
        System.out.println("enter string for d");
        String d=sc.next();
        System.out.println("d is "+d);
    }
}

산출:

enter string for c abc def
c is abc

enter string for d

d is def

If you use nextLine() instead of next() then

Output:

enter string for c

ABC DEF
c is ABC DEF
enter string for d

GHI
d is GHI


  • Just for another example of Scanner.next() and nextLine() is that like below : nextLine() does not let user type while next() makes Scanner wait and read the input.

     Scanner sc = new Scanner(System.in);
    
     do {
        System.out.println("The values on dice are :");
        for(int i = 0; i < n; i++) {
            System.out.println(ran.nextInt(6) + 1);
        }
        System.out.println("Continue : yes or no");
     } while(sc.next().equals("yes"));
    // while(sc.nextLine().equals("yes"));
    

A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.

Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position. NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line. so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().

 public static void main(String[] args) {
            // TODO code application logic here
           String str;
            Scanner input = new Scanner( System.in );
            str=input.nextLine();
            System.out.println(str);
       }

I also got a problem concerning a delimiter. the question was all about inputs of

  1. enter your name.
  2. enter your age.
  3. enter your email.
  4. enter your address.

The problem

  1. I finished successfully with name, age, and email.
  2. When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".

The solution

I used the delimiter for my scanner and went out successful.

Example

 public static void main (String args[]){
     //Initialize the Scanner this way so that it delimits input using a new line character.
    Scanner s = new Scanner(System.in).useDelimiter("\n");
    System.out.println("Enter Your Name: ");
    String name = s.next();
    System.out.println("Enter Your Age: ");
    int age = s.nextInt();
    System.out.println("Enter Your E-mail: ");
    String email = s.next();
    System.out.println("Enter Your Address: ");
    String address = s.next();

    System.out.println("Name: "+name);
    System.out.println("Age: "+age);
    System.out.println("E-mail: "+email);
    System.out.println("Address: "+address);
}

The basic difference is next() is used for gettting the input till the delimiter is encountered(By default it is whitespace,but you can also change it) and return the token which you have entered.The cursor then remains on the Same line.Whereas in nextLine() it scans the input till we hit enter button and return the whole thing and places the cursor in the next line. **

        Scanner sc=new Scanner(System.in);
        String s[]=new String[2];
        for(int i=0;i<2;i++){
            s[i]=sc.next();
        }
        for(int j=0;j<2;j++)
        {
            System.out.println("The string at position "+j+ " is "+s[j]);
        }

**

Try running this code by giving Input as "Hello World".The scanner reads the input till 'o' and then a delimiter occurs.so s[0] will be "Hello" and cursor will be pointing to the next position after delimiter(that is 'W' in our case),and when s[1] is read it scans the "World" and return it to s[1] as the next complete token(by definition of Scanner).If we use nextLine() instead,it will read the "Hello World" fully and also more till we hit the enter button and store it in s[0]. We may give another string also by using nextLine(). I recommend you to try using this example and more and ask for any clarification.

참고URL : https://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class

반응형